📜  c# linq distinct group by 嵌套列表 - C# (1)

📅  最后修改于: 2023-12-03 14:39:43.401000             🧑  作者: Mango

C# LINQ中的Distinct、Group By及嵌套列表操作

在C#语言中,使用LINQ可以轻松地实现对集合数据的查询、过滤和操作。本文将介绍LINQ中的Distinct、Group By及嵌套列表操作。

Distinct操作

Distinct操作可以去除集合中的重复数据,它可以应用于任何实现了IEquatable接口的类型,也可以自定义比较器。

代码示例:

List<int> numbers = new List<int> { 1, 2, 2, 3, 3, 3 };
IEnumerable<int> distinctNumbers = numbers.Distinct();
// distinctNumbers = {1, 2, 3}
Group By操作

Group By操作可以将集合按照指定的属性或条件进行分组,并返回一个IEnumerable<IGrouping<TKey, TElement>>类型的结果,其中TKey为分组依据的属性或条件的类型,TElement为集合中的元素类型。

代码示例:

List<Person> persons = new List<Person>
{
    new Person { Name = "张三", Age = 20, Sex = "男" },
    new Person { Name = "李四", Age = 18, Sex = "女" },
    new Person { Name = "王五", Age = 20, Sex = "男" },
    new Person { Name = "赵六", Age = 18, Sex = "女" }
};
IEnumerable<IGrouping<int, Person>> personsByAge = persons.GroupBy(p => p.Age);
/*
personsByAge = {
    {
        Key = 20,
        Values = [
            { Name = "张三", Age = 20, Sex = "男" },
            { Name = "王五", Age = 20, Sex = "男" }
        ]
    },
    {
        Key = 18,
        Values = [
            { Name = "李四", Age = 18, Sex = "女" },
            { Name = "赵六", Age = 18, Sex = "女" }
        ]
    }
}
*/
嵌套列表操作

嵌套列表操作可以将多个集合进行嵌套,并对其进行复杂的操作。

代码示例:

List<Student> students = new List<Student>
{
    new Student { Name = "张三", Age = 20, Scores = new List<int> { 80, 90, 70 } },
    new Student { Name = "李四", Age = 18, Scores = new List<int> { 75, 85, 95 } },
    new Student { Name = "王五", Age = 20, Scores = new List<int> { 90, 80, 80 } },
    new Student { Name = "赵六", Age = 18, Scores = new List<int> { 80, 85, 85 } }
};
IEnumerable<IGrouping<int, IEnumerable<IGrouping<int, Student>>>> studentsByAgeAndScore = students
    .GroupBy(s => s.Age)
    .Select(g1 => g1.GroupBy(s => s.Scores.Average() / 10))
    .ToList();
/*
studentsByAgeAndScore = {
    {
        Key = 2,
        Values = [
            {
                Key = 7,
                Values = [
                    { Name = "张三", Age = 20, Scores = [ 80, 90, 70 ] },
                    { Name = "王五", Age = 20, Scores = [ 90, 80, 80 ] }
                ]
            }
        ]
    },
    {
        Key = 1,
        Values = [
            {
                Key = 8,
                Values = [
                    { Name = "李四", Age = 18, Scores = [ 75, 85, 95 ] }
                ]
            },
            {
                Key = 8,
                Values = [
                    { Name = "赵六", Age = 18, Scores = [ 80, 85, 85 ] }
                ]
            }
        ]
    }
}
*/

以上是对C# LINQ中的Distinct、Group By及嵌套列表操作的简单介绍,这些操作可以帮助程序员更加高效地实现对集合数据的操作和处理。