Sort group item by attribute I have a repository method which retrieve a list of items, for example:



StaffID: 250026965
Name: Abbasov Islam
FreeTextName: NULL

StaffID: NULL
Name: NULL
FreeTextName: Antonio Puccio

StaffID: 358
Name: Prosinecki Robert
FreeTextName: NULL


I have to sort this list in this manner:

First the items with StaffID &gt; 0 by Name, then the items with StaffID == NULL by FreeTextName.

In the example case:

StaffID: 250026965
Name: Abbasov Islam
FreeTextName: NULL

StaffID: 358
Name: Prosinecki Robert
FreeTextName: NULL

StaffID: NULL
Name: NULL
FreeTextName: Antonio Puccio


At the moment I am doing:



var resList = conn.Query&lt;TeamSheetStaffPoco&gt;("[dbo].[TList]", p, commandType: CommandType.StoredProcedure).AsList();
var result = resList.Where(x =&gt; x.StaffID&gt; 0).OrderBy(y =&gt; y.Name).ToList();
result.AddRange(resList.Where(x =&gt; x.StaffID== null).OrderBy(y =&gt; y.FreeTextName).ToList());


It works, but I am not sure if exist a more concise and elegant mode to to do the same thing.
Use a custom IComparer&lt;T&gt; to sort the the items.

class TeamSheetStaffPocoComparer : IComparer&lt;TeamSheetStaffPoco&gt; {

    public int Compare(TeamSheetStaffPoco a, TeamSheetStaffPoco b) {

        if (a.StaffID == null &amp;&amp; b.StaffId == null)
        {
            return a.FreeTextName.CompareTo(b.FreeTextName);
        }

        if (a.StaffID &gt; 0 &amp;&amp; b.StaffID &gt; 0) 
        {
            return a.Name.CompareTo(b.Name);
        }

        return a.StaffID &gt; 0 ? 1 : -1;
    }

 }


Then you can simplify the last two lines to 

var result = resList.OrderBy(x =&gt; x, new TeamSheetStaffPocoComparer()).ToList();


Also, you can now reuse the comparison class elsewhere too if you wish.