Sorting a list of Person objects using Linq

I need a query to sort a list of objects based on the category of properties of objects. I need groups in a different order than the usual alphabetical order, which I saw in many other patterns. I am using an example that I took elsewhere. How can I generate a list of Person objects based on HomeProvince, but in terms of this ordering:

Ontario, Quebec, Alberta, Manitoba, British Columbia. The order in each group does not matter.

Person[] people = new Person[]
{
    new Person() { FirstName = "Tony", LastName = "Montana", Age = 39, HomeProvince = "Ontario" },
    new Person() { FirstName = "Bill", LastName = "Smith", Age = 23, HomeProvince = "Ontario" },
    new Person() { FirstName = "Jane", LastName = "Doe", Age = 23, HomeProvince = "Alberta" },
    new Person() { FirstName = "John", LastName = "Doe", Age = 23, HomeProvince = "Alberta" },
    new Person() { FirstName = "Alex", LastName = "DeLarge", Age = 19, HomeProvince = "British Columbia" },
    new Person() { FirstName = "Travis", LastName = "Bickle", Age = 42, HomeProvince = "Quebec" },
    new Person() { FirstName = "Ferris", LastName = "Beuller", Age = 17, HomeProvince = "Manitoba" },
    new Person() { FirstName = "Maggie", LastName = "May", Age = 23, HomeProvince = "Ontario" },
    new Person() { FirstName = "Mickey", LastName = "Mouse", Age = 93, HomeProvince = "Alberta" },
    new Person() { FirstName = "Frank", LastName = "Darabont", Age = 49, HomeProvince = "Ontario" }
};
+3
source share
2 answers

You can do it:

// Provinces in the desired order
string[] provinces = { "Ontario", "Quebec", "Alberta", "Manitoba", 
                       "British Columbia" };

var query = from province in provinces
            join person in people on province equals person.HomeProvince
            select person;

It will be basically:

  • Ignore anyone not listed in the specified provinces.
  • Returns the sequence of people in the specified province order

, , :

var query = from province in provinces
            join person in people on province equals person.HomeProvince
                into grouped
            select new { Province = province, People = grouped.ToList() };

- "" . , .

+5

, , , , Ontario HomeProvince . ... , "".

, , . , , , , , .

0

All Articles