在c#中如何實(shí)現(xiàn)自定義的分組邏輯

c#
小樊
87
2024-09-20 08:09:25

在C#中,你可以通過(guò)實(shí)現(xiàn)IEnumerable<T>.GroupBy<TKey>方法來(lái)自定義分組邏輯。以下是一個(gè)示例:

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();

        // 輸出結(jié)果
        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; }
}

在這個(gè)示例中,我們首先創(chuàng)建了一個(gè)Person列表。然后,我們使用GroupBy方法按城市對(duì)人員進(jìn)行分組。我們提供了一個(gè)自定義的匿名類型作為分組的鍵,并將分組后的結(jié)果存儲(chǔ)在一個(gè)名為groupedPeople的列表中。最后,我們遍歷groupedPeople列表并輸出每個(gè)分組的城市和人員信息。

0