在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#中的多樣性和實用性。你可以根據你的具體需求調整分組依據和后續操作。