Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 379
Maximus Decimus Avatar asked Oct 25 '13 13:10

Maximus Decimus


3 Answers

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).
like image 64
Jon Skeet Avatar answered Nov 07 '22 00:11

Jon Skeet


Sure -

list.GroupBy(t => t.GetType());

Will give you a collection of collections group by type.

like image 26
D Stanley Avatar answered Nov 07 '22 01:11

D Stanley


You can use Enumerable.OfType

var newList1 = list.OfType<Object1>().ToList()
var newList2 = list.OfType<Object2>().ToList()
var newList3 = list.OfType<Object3>().ToList()

As mentioned by Jon skeet in one of the comments, above has issues when there is inheritance in picture (ie Object1 derives form Object2). If that is the case, Only option is to compare using type

var newList1 = list.Where(t=>t.GetType() == typeof(Object1)).ToList()
var newList2 = list.Where(t=>t.GetType() == typeof(Object2)).ToList()
var newList3 = list.Where(t=>t.GetType() == typeof(Object3)).ToList()
like image 4
Tilak Avatar answered Nov 06 '22 23:11

Tilak