I can write some code that loops the original list and adds each item to the new list based on the attribute value, but it doesn’t seem to be easy to maintain (if I suddenly get a ValueD, then What should I do?)
**Edit. I should mention that I am using version 2.0 of the framework.
//if PropertyA is not int , change int to whatever that type is
Dictionary> myCollections =
new Dictionary>();
//
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());
}
//now add the value to the entry.
myCollections[myFoo .PropertyA].Add(myFoo);
}
//
// now recollect these lists into the result.
List> result = new List< List
>();
foreach(ListsomeFoos in myCollections.Values)
{
result.Add(someFoos);
}
< p>Now, I only write:
List> resul t = fooList
.GroupBy(foo => foo.PropertyA)
.Select(g => g.ToList())
.ToList();
ILookup> result = fooList.ToLookup(foo => foo.PropertyA);
I have a generic List (Foo) which contains n objects of Type Foo. One property of Foo is PropertyA. PropertyA can be one of ValueA, ValueB or ValueC. Is there a simple way to divide it into three A separate list, one for ValueA, one for ValueB, and one for ValueC?
I can write some code that loops the original list and adds each item to the new list based on the attribute value, but it doesn’t seem to be easy to maintain (if I suddenly get a ValueD, then What should I do?)
**Edit. I should mention that I am using version 2.0 of the framework.
In C# and In .Net 2.0, I wrote (too many times):
//if PropertyA is not int, change int to whatever that type is
Dictionary> myCollections =
new Dictionary>();
//
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());
}
//now add the value to the entry.
myCollections[myFoo.PropertyA].Add(myFoo);
)
//
// now recollect these lists into the result.
List> result = new List
>();
foreach(ListsomeFoos in myCollections.Values)
{
result.Add(someFoos);
}
Now, I only write:
List> result = fooList
.GroupBy(foo => foo.PropertyA)
. Select(g => g.ToList())
.ToList();
or
ILookup> result = fooList.ToLookup(foo => foo.PropertyA);