.NET – How to split universal list (t) based on the attributes of the list

I have a generic List(Foo), which contains n objects of Type Foo. A property of Foo is PropertyA. PropertyA can be one of ValueA, ValueB or ValueC. Yes Is there no easy way to divide it into three separate lists, 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 .Net 2.0, I have written (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< List>();
foreach(List someFoos 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(List someFoos 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);

Leave a Comment

Your email address will not be published.