使用一些LINQ中,集團通過密鑰,然後以5:
var data = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("Harry", "1"),
new KeyValuePair<string, string>("Harry", "2"),
new KeyValuePair<string, string>("Harry", "3"),
new KeyValuePair<string, string>("Harry", "4"),
new KeyValuePair<string, string>("Harry", "5"),
new KeyValuePair<string, string>("Harry", "6"),
new KeyValuePair<string, string>("Harry", "7"),
new KeyValuePair<string, string>("Sally", "1"),
new KeyValuePair<string, string>("Sally", "2"),
new KeyValuePair<string, string>("Sally", "3"),
new KeyValuePair<string, string>("Sally", "4"),
new KeyValuePair<string, string>("Sally", "5"),
new KeyValuePair<string, string>("Sally", "6"),
};
var output = data.GroupBy(x => x.Key)
.SelectMany(x => x.Take(5));
foreach (var item in output)
{
Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
}
輸出將是
Key: Harry, Value: 1
Key: Harry, Value: 2
Key: Harry, Value: 3
Key: Harry, Value: 4
Key: Harry, Value: 5
Key: Sally, Value: 1
Key: Sally, Value: 2
Key: Sally, Value: 3
Key: Sally, Value: 4
Key: Sally, Value: 5
Press any key to continue . . .
一個問題,雖然。爲什麼在使用字典時使用KeyValuePairs的列表?如果有的話,你可以使用一個'Dictionary>',它附帶了預先分組的名稱。 –
Abion47