c#, Uncategorized

Ordering in LINQ by alphabetical order except for 1 item!

I wanted to alphabetically order a list of objects containing prices and names for a DropDownList, except I wanted the “No Cost” option (which was in the list with a zero price) to be at the top of the list.

What I needed to do was sort a list first by whether the item’s name was “No Cost”, and then by alphabetical order, so after a bit of Googling I discovered this technique of first ordering by whether the name was “No Cost” or not, and then by alphabetical order:

var items = GetProducts().
    OrderBy(x => x.Name != "No Cost").
    ThenBy(x => x.Name);

ddl.DataSource = items;