Grouping collections of the same type C #

I have a set of differents objects and I want to know if I can create collections that group objects of the same type. 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 need 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 
+6
source share
4 answers

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

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

You can:

  • Iterate over it to find all types and related objects.
  • Retrieve all elements of a specific type using the indexer. If you specify a type that is not in the search, this will return an empty sequence (which is really useful, and does not throw an exception or return null).
+15
source

You can use Enumerable.OfType

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

As Jon skeet mentioned in one of the comments, the above have problems when there is inheritance in the image (i.e., Object1 gets the form Object2). If so, the 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() 
+4
source

Sure -

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

A collection of collections by type will be presented.

+4
source

You mean the following:

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

?

+2
source

Source: https://habr.com/ru/post/956717/


All Articles