views:

79

answers:

4

I have a table with a list of countries in it that I'm using to populate a dropdown.

How can I construct a LINQ query so it will return the list of countries from that table in alphabetical order, with the exception of placing USA at the top?

So, if the table contained:

Sweden
USA
Mexico
Denmark

It would return:

USA
Denmark
Mexico
Sweden

?

A: 
  1. Add USA to the dropdown.

  2. Add a list of alphabetically sorted countries afterwords.

The drop down control will preserve the order you added the items in.

jfar
+2  A: 

Try this (a one-liner):

var Countries = new List<string>() { "Denmark", "USA", "Mexico" };
return Countries.OrderBy(c=> c=="USA"? " ": c);

Explanation:

This sorts the list of countries by name, subsituting " " for the one that should be first. Since whitespace comes before any other letter alphabetically, the "default" country will be listed first.

Michael Haren
+4  A: 

You can use the country's name as a secondary ordering:

return countries.OrderBy(c => GetPrimaryOrdering(c)).ThenBy(c => c.Name);

int GetPrimaryOrdering(Country country) 
{ 
    return country.Name == "USA" ? 0 : 1
}
Avish
A: 

Ridiculous ...

var lst = new List<string>()
  { "Sweden", "USA", "Mexico", "Denmark", "Ziptown" };

lst.Sort((x, y) =>
{
  if (x == "USA" || y == "USA")
  {
    if (x == y)
    {
       return 0;
    }

    return (x == "USA") ? -1 : 1;
  }
  else
  {
    return x.CompareTo(y);     
  }
}
JP Alioto