How can I use LINQ to return a list of countries, but by placing a specific country aribitrarly at the top?

I have a table with a list of countries in which I use to populate a drop-down list.

How can I build a LINQ query to return a list of countries from this table in alphabetical order, with the exception of placing the USA at the top?

So, if the table contains:

Sweden
USA Singles Mexico
Denmark

He will return:

USA Singles Denmark
Mexico
Sweden

?

+3
source share
4 answers

You can use the name of the country as a secondary order:

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

int GetPrimaryOrdering(Country country) 
{ 
    return country.Name == "USA" ? 0 : 1
}
+5
source

Try this (single line):

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

Explanation:

, "" , . , .

+3
  • Add the USA to the drop-down list.

  • Add a list of alphabetically sorted countries after the words.

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

0
source

It's funny ...

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);     
  }
}
0
source

Source: https://habr.com/ru/post/1710378/


All Articles