Maximus Decimus
Maximus Decimus

Reputation: 5311

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 

Upvotes: 10

Views: 7718

Answers (4)

Tilak
Tilak

Reputation: 30728

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()

Upvotes: 4

user610217
user610217

Reputation:

You mean like this:

var newList1 = list.OfType<Object1>().ToList();

?

Upvotes: 3

D Stanley
D Stanley

Reputation: 152626

Sure -

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

Will give you a collection of collections group by type.

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1502716

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).

Upvotes: 20

Related Questions