首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

使用LINQ如何通过"计算字段"进行分组

使用LINQ通过“计算字段”进行分组,可以使用GroupBy方法和Select方法来实现。以下是一个简单的示例,假设我们有一个Student类,其中包含NameAge属性,我们想要根据年龄段对学生进行分组,并计算每个年龄段的平均年龄。

代码语言:csharp
复制
using System;
using System.Collections.Generic;
using System.Linq;

class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        List<Student> students = new List<Student>
        {
            new Student { Name = "Tom", Age = 18 },
            new Student { Name = "Jerry", Age = 20 },
            new Student { Name = "Alice", Age = 19 },
            new Student { Name = "Bob", Age = 21 },
            new Student { Name = "Cathy", Age = 22 }
        };

        var result = students.GroupBy(s => GetAgeGroup(s.Age))
                            .Select(g => new
                            {
                                AgeGroup = g.Key,
                                AverageAge = g.Average(s => s.Age)
                            });

        foreach (var item in result)
        {
            Console.WriteLine($"Age group: {item.AgeGroup}, Average age: {item.AverageAge}");
        }
    }

    static string GetAgeGroup(int age)
    {
        if (age < 20)
        {
            return "Under 20";
        }
        else if (age < 25)
        {
            return "20-24";
        }
        else
        {
            return "Over 25";
        }
    }
}

在这个示例中,我们首先定义了一个Student类,其中包含NameAge属性。然后,我们创建了一个List<Student>对象,其中包含了一些示例学生。接下来,我们使用GroupBy方法和Select方法对学生进行分组和计算平均年龄。

GetAgeGroup方法用于将学生的年龄划分为不同的年龄段。在这个示例中,我们将年龄小于20岁的学生划分为“Under 20”年龄段,将年龄在20岁到24岁之间的学生划分为“20-24”年龄段,将年龄大于25岁的学生划分为“Over 25”年龄段。

最后,我们使用foreach循环遍历结果,并输出每个年龄段的平均年龄。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券