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
LINQ can do this very easily returning a single lookup collection:
var lookup = list.ToLookup(x => x.GetType());
You can then:
Sure -
list.GroupBy(t => t.GetType());
Will give you a collection of collections group by type.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With