在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
列表并輸出每個分組的城市和人員信息。