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;




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s