EKsumic's Blog

The current theme of this website is Japanese learning.

Click the left button to use the catalog.

OR

[新手入门]C#关于Groupby到底如何使用?

准备要使用的List,用于分组(GroupBy):

List<Person> personList = new List<Person>
{
    new Person
    {
        Name = "P1", Age = 18, Gender = "Male"

    },
    new Person
    {
        Name = "P2", Age = 19, Gender = "Male",
    },
    new Person
    {
        Name = "P2", Age = 17,Gender = "Female",
    }
};

最常用的方式:

var groups = personList.GroupBy(p => p.Gender, p => p.Name);
foreach (var group in groups)
{
    Console.WriteLine(group.Key.ToString());
    foreach (var name in group)
    {
        Console.WriteLine($"\t{name}");
    }
}

输出结果:

Male
    P1
    P2
Female
    P3

可见group本视是一个集合,当里面的元素只有1个的时候,你还是得以foreach的方式取得name,具体实例见:

关于PCRArenaRecorder&Analyzer的概率分析相关逻辑代码

这里面已经FirstOrDefault()出来了,但还是得foreach,不然你只能得到key,得不到key所对用的内容。

 

参考文档:

https://www.cnblogs.com/zxs-onestar/p/11202402.html

This article was last edited at 2020-09-11 23:21:49

* *