温馨提示×

在c#中如何实现自定义的分组逻辑

c#
小樊
88
2024-09-20 08:09:25
栏目: 编程语言

在C#中,你可以通过实现IEnumerable<T>.GroupBy<TKey>方法来自定义分组逻辑。以下是一个示例:

using System;
using System.Collections.Generic;
using System.Linq;

class CustomGrouping
{
    static void Main()
    {
        var people = new List<Person>
        {
            new Person { Name = "Alice", Age = 30, City = "New York" },
            new Person { Name = "Bob", Age = 25, City = "San Francisco" },
            new Person { Name = "Charlie", Age = 30, City = "New York" },
            new Person { Name = "David", Age = 28, City = "San Francisco" },
            new Person { Name = "Eva", Age = 25, City = "Los Angeles" }
        };

        // 自定义分组逻辑
        var groupedPeople = people.GroupBy(p => p.City, (city, group) =>
        {
            return new
            {
                City = city,
                People = group.OrderBy(p => p.Name).ToList()
            };
        }).ToList();

        // 输出结果
        foreach (var group in groupedPeople)
        {
            Console.WriteLine($"City: {group.City}");
            foreach (var person in group.People)
            {
                Console.WriteLine($"  {person.Name}, {person.Age}");
            }
        }
    }
}

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string City { get; set; }
}

在这个示例中,我们首先创建了一个Person列表。然后,我们使用GroupBy方法按城市对人员进行分组。我们提供了一个自定义的匿名类型作为分组的键,并将分组后的结果存储在一个名为groupedPeople的列表中。最后,我们遍历groupedPeople列表并输出每个分组的城市和人员信息。

0