2

The title is perhaps a little confusing (please change if it is)

I have a list of objects, example is:

public class MyObj{
  public int ID {get;set;}
  public string MyType {get;set;}
}

Let's say I have a List<MyObj> that contains 4 elements.

The types on each of these are:

myObj1.MyType = "ABC";
myObj2.MyType = "7551";
myObj3.MyType = "AAABB";
myObj3.MyType = "CDE";

I would like to, if possible, order this list so that "ABC" has the most weight and comes first. The rest of the list can be sorted alphabetically.

I'm in .Net 4.5 so can use the Comparer<>.Create() - i just have no idea how to do what I need to do.

Darren Wainwright
  • 30,247
  • 21
  • 76
  • 127
  • Might you want to create your own custom encoding - http://stackoverflow.com/questions/17386062/use-a-custom-encoding-or-add-custom-characters – David P Nov 10 '15 at 15:32

1 Answers1

7

I would guess something like this would work (and without the need for Comparers)

myList.OrderByDescending(o=>o.MyType == "ABC").ThenBy(o=>o.MyType);

Basically, it orders the list by whether it is ABC or not (and floats them to the top), then the remainder is ordered normally.

The reason the first OrderBy clause is Descending is that false comes before true, so in order to float the ABCs to the top, it needs to sort in reverse.

Colin Mackay
  • 18,736
  • 7
  • 61
  • 88