.net – 如何根据列表成员的属性拆分通用List(T)?
发布时间:2020-12-17 07:11:53 所属栏目:百科 来源:网络整理
导读:我有一个通用的List(Foo),它包含了Type Foo的n个对象. Foo的一个属性是PropertyA. PropertyA可以是ValueA,ValueB或ValueC之一.有没有一种简单的方法可以将它分成三个单独的列表,一个用于ValueA,一个用于ValueB,一个用于ValueC? 我可以编写一些循环原始列表
我有一个通用的List(Foo),它包含了Type Foo的n个对象. Foo的一个属性是PropertyA. PropertyA可以是ValueA,ValueB或ValueC之一.有没有一种简单的方法可以将它分成三个单独的列表,一个用于ValueA,一个用于ValueB,一个用于ValueC?
我可以编写一些循环原始列表的代码,并根据属性值将每个项目添加到新列表中,但这似乎不是很容易维护(如果我突然得到一个ValueD,那该怎么办?) **编辑.我应该提到我正在使用该框架的2.0版本. 解决方法
在C#和.Net 2.0中,我写过(太多次):
//if PropertyA is not int,change int to whatever that type is Dictionary<int,List<foo>> myCollections = new Dictionary<int,List<foo>>(); // foreach(Foo myFoo in fooList) { //if I haven't seen this key before,make a new entry if (!myCollections.ContainsKey(myFoo.PropertyA)) { myCollections.Add(myFoo.PropertyA,new List<foo>()); } //now add the value to the entry. myCollections[myFoo.PropertyA].Add(myFoo); } // // now recollect these lists into the result. List<List<Foo>> result = new List<List<Foo>>(); foreach(List<Foo> someFoos in myCollections.Values) { result.Add(someFoos); } 如今,我只写: List<List<foo>> result = fooList .GroupBy(foo => foo.PropertyA) .Select(g => g.ToList()) .ToList(); 要么 ILookup<TypeOfPropertyA,foo>> result = fooList.ToLookup(foo => foo.PropertyA); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |