在C#中,GroupBy
是一个非常强大的LINQ(Language Integrated Query)方法,它允许你根据某个或某些属性将集合中的元素进行分组。以下是一些GroupBy
在C#中的常见应用场景:
按类型分组:
假设你有一个对象列表,每个对象都有一个类型属性,你可以使用GroupBy
来按这个类型属性对这些对象进行分组。
var people = new List<Person>
{
new Person { Name = "Alice", Age = 25, Type = "Student" },
new Person { Name = "Bob", Age = 30, Type = "Employee" },
new Person { Name = "Charlie", Age = 25, Type = "Student" },
new Person { Name = "David", Age = 30, Type = "Employee" }
};
var groupedPeople = people.GroupBy(p => p.Type);
foreach (var group in groupedPeople)
{
Console.WriteLine($"Group: {group.Key}");
foreach (var person in group)
{
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}
按日期分组:
如果你有一个包含多个日期的对象列表,你可以使用GroupBy
来按日期对这些对象进行分组。
var events = new List<Event>
{
new Event { Date = new DateTime(2023, 1, 1), Name = "New Year's Day" },
new Event { Date = new DateTime(2023, 1, 10), Name = "Rainy Day" },
new Event { Date = new DateTime(2023, 2, 14), Name = "Valentine's Day" },
new Event { Date = new DateTime(2023, 2, 14), Name = "Rainy Day" }
};
var groupedEvents = events.GroupBy(e => e.Date.Date);
foreach (var group in groupedEvents)
{
Console.WriteLine($"Date: {group.Key}");
foreach (var @event in group)
{
Console.WriteLine($"Name: {@event.Name}");
}
}
按地区分组:
如果你有一个包含多个销售记录的对象列表,每个记录都有一个地区属性,你可以使用GroupBy
来按地区对这些记录进行分组,并计算每个地区的总销售额。
var sales = new List<Sale>
{
new Sale { Region = "North", Amount = 1000 },
new Sale { Region = "South", Amount = 1500 },
new Sale { Region = "East", Amount = 750 },
new Sale { Region = "West", Amount = 1250 },
new Sale { Region = "South", Amount = 500 }
};
var groupedSales = sales.GroupBy(s => s.Region).ToDictionary(g => g.Key, g => g.Sum(s => s.Amount));
foreach (var region in groupedSales.Keys)
{
Console.WriteLine($"Region: {region}, Total Sales: {groupedSales[region]}");
}
按字符串的首字母分组: 你可以按字符串的首字母对字符串数组进行分组,这在创建字典或进行其他需要分组的操作时非常有用。
var words = new string[] { "Apple", "Banana", "Cherry", "Date", "Elderberry" };
var groupedWords = words.GroupBy(w => w[0]);
foreach (var group in groupedWords)
{
Console.WriteLine($"First Letter: {group.Key}");
foreach (var word in group)
{
Console.WriteLine(word);
}
}
这些示例展示了GroupBy
在C#中的多样性和实用性。你可以根据你的具体需求调整分组依据和后续操作。