我需要执行以下操作,我有一个List包含2个整数id和count的类
现在我想做以下linq查询:
get the sum of the count for each id
Run Code Online (Sandbox Code Playgroud)
但是可能存在具有相同id的项目,因此应该对其进行总结,例如:
id=1, count=12
id=2, count=1
id=1, count=2
Run Code Online (Sandbox Code Playgroud)
应该是:
id=1 -> sum 14
id=2 -> sum 1
Run Code Online (Sandbox Code Playgroud)
这该怎么做?
可能重复:
是否有LINQ方式从键/值对列表转到字典?
假设我有List<string>如下:
var input = new List<string>()
{
"key1",
"value1",
"key2",
"value2",
"key3",
"value3",
"key4",
"value4"
};
Run Code Online (Sandbox Code Playgroud)
根据这个列表,我想转换为List<KeyValuePair<string, string>>,原因是允许相同的键,这就是为什么我不使用Dictionary.
var output = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("key1", "value1"),
new KeyValuePair<string, string>("key2", "value2"),
new KeyValuePair<string, string>("key3", "value3"),
new KeyValuePair<string, string>("key4", "value4"),
};
Run Code Online (Sandbox Code Playgroud)
我可以通过使用下面的代码来实现:
var keys = new List<string>();
var values = new List<string>();
for (int index = 0; index < input.Count; index++)
{
if (index % 2 == 0) keys.Add(input[index]);
else values.Add(input[index]);
}
var …Run Code Online (Sandbox Code Playgroud)