如何查询T组列表

本文关键字:列表 查询 何查询 | 更新日期: 2023-09-27 18:28:52

我有以下类。

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的属性,如下所示,它创建了一个按国家/地区列出的Group。因此,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");

如何查询T组列表

vm.DataList.SingleOrDefault(g => g.Any(x => x.Name == "Milan"))