Grouping collections of the same type C#

I have a collection of differents objects and I want to know if I can create collections grouping the same type of objects. I don't know if there is a method with linq or something like that.

List<Object> list = new List<Object>();
Object1 obj1 =  new Object1();
Object2 obj2 =  new Object2();
Object1 obj3 =  new Object1();
Object3 obj4 =  new Object3();
Object3 obj5 =  new Object3();

list.Add(obj1);
list.Add(obj2);
list.Add(obj3);
list.Add(obj4);
list.Add(obj5);

I want new lists of the same type:

List<Object1> newList1 = method.GetAllObjectsFromListObject1 // Count = 2
List<Object2> newList2 = //GetAllObjectsFromListObject2 // Count = 1
List<Object3> newList3 = //GetAllObjectsFromListObject3 // Count = 2 
Jon Skeet
people
quotationmark

LINQ can do this very easily returning a single lookup collection:

var lookup = list.ToLookup(x => x.GetType());

You can then:

  • Iterate over it to find all the types and the associated objects
  • Fetch all the items of a specific type using the indexer. If you specify a type which isn't present in the lookup, this will return an empty sequence (which is really useful, rather than throwing an exception or returning null).

people

See more on this question at Stackoverflow