Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a collection based on type in LINQ

Tags:

c#

linq

.net-3.5

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.

like image 606
jaks Avatar asked Oct 06 '10 16:10

jaks


2 Answers

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.

like image 191
Jon Hanna Avatar answered Oct 05 '22 18:10

Jon Hanna


collection.OrderBy(i => i.GetType() == typeof(A) ? 0 : 1);

Will give you a sequence with all the As then all the Bs

like image 23
Lee Avatar answered Oct 05 '22 19:10

Lee