I have a collection like this,
Class Base{}
Class A : Base {}
Class B : Base {}
List<Base> collection = new List<Base>();
collection.Add(new A());
collection.Add(new B());
collection.Add(new A());
collection.Add(new A());
collection.Add(new B());
Now I want to sort the collection based on type (A/B). How I can do this? Please help me.
private static int OrderOnType(Base item)
{
if(item is A)
return 0;
if(item is B)
return 1;
return 2;
}
Then take your pick from:
collection.OrderBy(OrderOnType)
or
collection.Sort((x, y) => OrderOnType(x).CompareTo(OrderOnType(y)));
Depending on whether you want in-place sorting or not. You could put OrderOnType into the lambda if you really wanted, but this seems more readable to me, and I prefer to keep lambdas for when they add rather than reduce readability.
collection.OrderBy(i => i.GetType() == typeof(A) ? 0 : 1);
Will give you a sequence with all the A
s then all the B
s
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