gpt4 book ai didi

c# - C#根据类成员将单个类对象List分成多个List

转载 作者:行者123 更新时间:2023-11-30 13:54:13 24 4
gpt4 key购买 nike

我有一个如下所示的 Person 类:

public class Person
{
public Person() { }
public Person(string name, int age, GenderType gender, string country) { Name = name; Age = age; Gender = gender; Country = country; }

public string Name { get; set; }
public int Age { get; set; }
public GenderType Gender { get; set; } // GenderType = M/F
public string Country { get; set; }
}

我想首先根据性别将此列表分成两个列表。然后我想根据国家/地区进一步将每个列表划分为子列表。因此,如果我在原始列表中有 n 个不同的国家/地区,那么最后我会得到 n 到 2n 个列表。下面的例子将进一步说明这个想法:

假设我原来的列表是这样的:

Sam, 23, M, USA
Jon, 13, M, USA
Jen, 26, F, USA
Thilini, 25, F, Sri Lanka
Anna, 23, F, UK
Chelsea, 35, F, UK
Saman, 43, M, Sri Lanka
Dan, 27, M, UK

第一师:

Male lists:
Sam, 23, M, USA
Jon, 13, M, USA
Saman, 43, M, Sri Lanka
Dan, 27, M, UK

------------------

Female lists:
Jen, 26, F, USA
Thilini, 25, F, Sri Lanka
Anna, 23, F, UK
Chelsea, 35, F, UK

然后进一步分割列表:

Male sub-list 1:
Sam, 23, M, USA
Jon, 13, M, USA

Male sub-list 2:
Saman, 43, M, Sri Lanka

Male sub-list 3:
Dan, 27, M, UK

------------------

Female sub-list 1:
Jen, 26, F, USA

Female sub-list 2:
Thilini, 25, F, Sri Lanka

Female sub-list 3:
Anna, 23, F, UK
Chelsea, 35, F, UK

我可以使用 foreach 循环轻松地做到这一点,并可能使用 Results 类遍历每个项目。但我想了解如何使用 Linq GroupBy() 和 Distinct() 来做到这一点?

我使用 GroupBy() 根据性别将其分成两个列表,如下所示。

static void Main(string[] args)
{
List<Person> people = new List<Person>()
{
new Person("Sam", 23, GenderType.M, "USA"),
new Person("Jon", 13, GenderType.M, "USA"),
new Person("Jen", 26, GenderType.F, "USA"),
new Person("Thilini", 25, GenderType.F, "Sri Lanka"),
new Person("Anna", 23, GenderType.F, "UK"),
new Person("Chelsea", 35, GenderType.F, "UK"),
new Person("Saman", 43, GenderType.M, "Sri Lanka"),
new Person("Dan", 27, GenderType.M, "UK")
};

var maleList = people.GroupBy(x => x.Gender).Where(y => y.Key == GenderType.M);
var femaleList = people.GroupBy(x => x.Gender).Where(y => y.Key == GenderType.F);

Console.ReadLine();
}

我不明白现在如何根据国家/地区将每个列表再分割为多个。

最佳答案

简单地通过复合键进行分组:

var groups = people.GroupBy(p => new { p.Gender, p.Country });

然后您可以迭代组并显示结果:

foreach(var group in groups.OrderBy(g => g.Key.Gender).ThenBy(g => g.Key.Country))
{
Console.WriteLine($"{group.Key.Gender} sub list {group.Key.Country}");

foreach(var person in group)
Console.WriteLine($"{person.Name} {person.Age} {person.Gender} {person.Country}");
}

关于c# - C#根据类成员将单个类对象List分成多个List,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45178913/

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