开发者

Sort a list of Person objects using Linq

I need a query on sorting list of objects based on the category of property of the objects. I need the groups to be in an order other than the usual alphabetical order which I have seen in many other samples. I am using an example I took from 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 ordering within 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 =开发者_StackOverflow中文版 "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" }
};


You could do this:

// 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;

That will basically:

  • Ignore anyone not in the specified provinces
  • Return a sequence of people in the province order specified

If you need the people grouped by province, that's easy too:

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

Another option would be to create a mapping from province to "priority" and simply order by that. It really depends on exactly what you need as output.


I'm not sure if this is the best way but I would probably just get every person with Ontario as HomeProvince and add them to the array. Then repeat for Quebec and so on... I don't know any other way because what you need is "random".

I say array because that's what you used in your code sample. Obviously it doesn't matter what kind of container you use as long as you don't order them as you put them in or after they are in.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜