Search code examples
c#arrayslinqsorting

How to order by an array of object in C# by using another array


Example I have a data

Person = [
  {
    Name: "AE1",
    Country: "PH"
  },
  {
    Name: "AE2",
    Country: "LD"
  },
  {
    Name: "AE3",
    Country: "TW"
  },
]

I want to order it by country lets say I put an const array of ["TW", "PH", "LD"].

The result would be AE3, AE1, AE2.


Solution

  • You can use Array.IndexOf as sort criteria:

    string[] countryOrders = {"GB", "TW", "SE"};
    var personsByCountry = persons.OrderBy(p => Array.IndexOf(countryOrders, p.Country));
    

    If a country does not exists it would come first, because -1 is returned. If you don't want that:

     var personsByCountry = persons
        .Select(p => (Person: p, Order: Array.IndexOf(countryOrders, p.Country)))
        .OrderBy(x => x.Order == -1 ? 1 : 0)
        .ThenBy(x => x.Order)
        .Select(x => x.Person);