gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:57:41 25 4
gpt4 key购买 nike

我需要查询基于对象属性类别的对象排序列表。我需要这些组的顺序不同于我在许多其他示例中看到的通常的字母顺序。我正在使用从其他地方获取的示例。我如何根据 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" }
};

最佳答案

你可以这样做:

// 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() };

另一种选择是创建一个从省份到“优先级”的映射,然后简单地按它排序。这实际上完全取决于您需要什么作为输出。

关于linq - 使用 Linq 对 Person 对象列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5360876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com