使用一些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