Search code examples
c#linq.net-3.5

How to sort a collection based on type in LINQ


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.


Solution

  • You can use the type information itself:

    collection.Sort( (a,b) => 
      {
          bool aType = a.GetType() == typeof(A);
          bool bType = b.GetType() == typeof(A);
          return aType.CompareTo(bType);
      });
    

    This will work for the two types you specified, but doesn't scale beyond them. It does allow you to specify the order explicitly (ie: if you want "B" elements before "A", you could make it work using this technique).

    If you need to support many types, and the ordering doesn't need to be specified in advance, you could do something like:

    collection.Sort( (a,b) => a.GetType().FullName.CompareTo(b.GetType().FullName) );
    

    This would handle any number of types (ie: a C and a D subtype, too), and order them by their full type name.