使用Linq对Person对象列表进行排序

时间:2011-03-19 07:55:06

标签: linq

我需要根据对象的属性类别对对象列表进行查询。我需要这些组的顺序不是我在许多其他样本中看到的通常的字母顺序。我正在使用我从其他地方带来的一个例子。如何基于HomeProvince生成Person对象列表,但是按照此顺序生成:

安大略省,魁北克省,艾伯塔省,马尼托巴省,不列颠哥伦比亚省。每组中的排序无关紧要。

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" }
};

2 个答案:

答案 0 :(得分:5)

你可以这样做:

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

基本上会这样:

  • 忽略不在指定省份的人
  • 按照指定的省份顺序返回一系列人员

如果您需要省按分组的人,那也很容易:

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

另一个选择是创建从省到“优先级”的映射,然后按顺序排序。这实际上取决于您需要的输出。

答案 1 :(得分:0)

我不确定这是否是最好的方法,但我可能只是将安大略省的每个人都作为HomeProvince并将它们添加到阵列中。然后重复魁北克等等......我不知道任何其他方式,因为你需要的是“随机”。

我说数组,因为这是你在代码示例中使用的内容。显然,只要你在放入或放入它们之后没有订购它们,你使用哪种容器并不重要。