我有跟随课程。
public class City
{
public string Name { get; set; }
public string Country { get; set; }
public string Language { get; set; }
}
.
public class Group<T> : List<T>
{
public Group(string name, IEnumerable<T> items)
: base(items)
{
this.Title = name;
}
public string Title
{
get;
set;
}
}
在我的类(myViewModel
)的构造函数中,我做了这样的事情
cityList = new List<City>();
cityList.Add(new City() { Name = "Milan", Country = "IT", Language = "Italian" });
cityList.Add(new City() { Name = "Roma", Country = "IT", Language = "Italian" });
cityList.Add(new City() { Name = "Madrid", Country = "ES", Language = "Spanish" });
现在,我公开了一个名为 DataList
如下所示的属性,该属性创建了一个国家/地区列表组。因此,DataList.Count = 2
public List<Group<City>> DataList
{
get
{
_datalist = GetCityGroups();
return _datalist;
}
}
public static List<Group<City>> GetCityGroups()
{
IEnumerable<City> cityList = GetCityList();
return GetItemGroups(cityList, c => c.Country);
}
private static List<Group<T>> GetItemGroups<T>(IEnumerable<T> itemList, Func<T, string> getKeyFunc)
{
IEnumerable<Group<T>> groupList = from item in itemList
group item by getKeyFunc(item) into g
orderby g.Key
select new Group<T>(g.Key, g);
return groupList.ToList();
}
现在,对于给定的名称(比如 Milan),我需要找到它属于哪个组(DataList[0] 或 DataList[1])。我该怎么做 ?
我想避免硬编码,如下所示
Group<City> g = vm.DataList[0]; // remove this hardcoded 0 here...
City c = g.FindLast(x => x.Name == "Milan");