我有一个通用的List(Foo),它包含了Type Foo的n个对象. Foo的一个属性是PropertyA. PropertyA可以是ValueA,ValueB或ValueC之一.有没有一种简单的方法可以将它分成三个单独的列表,一个用于ValueA,一个用
我可以编写一些循环原始列表的代码,并根据属性值将每个项目添加到新列表中,但这似乎不是很容易维护(如果我突然得到一个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);
