DMS DMS - 1 year ago 125
C# Question

C# list sort by two columns

I have a C# custom object list that I need to sort by two different variables one is a boolean and the other is a string. I can sort by either of the criteria, but I'm having trouble figuring out how to combine them. The sort should be all of the boolean values first (CheckedIn) and then the last name for each of the values. Right now I use

result.Sort((x, y) => string.Compare(x.CheckedIn.ToString(), y.CheckedIn.ToString()));
result.Sort((x, y) => string.Compare(x.LastName, y.LastName));

But how can I combine then so that my results are like

No - Aames
No - Smith
Yes - Barnes
Yes - Peters

Answer Source
result.Sort((x,y) => x.CheckedIn==y.CheckedIn ? 
  string.Compare(x.LastName, y.LastName) : 
  (x.CheckedIn ? -1 : 1) );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download