我跟随课程。
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();
}
现在,对于给定的名称(比如米兰),我需要找到它属于哪个组(DataList [0]或DataList [1])。我该怎么做?
我想避免硬编码,如下所示
Group<City> g = vm.DataList[0]; // remove this hardcoded 0 here...
City c = g.FindLast(x => x.Name == "Milan");
答案 0 :(得分:2)
vm.DataList.SingleOrDefault(g => g.Any(x => x.Name == "Milan"))