SortedDictionary<int, string> typeDictionary = new SortedDictionary<int, string>();
SortedDictionary<int, int> lengthDictionary = new SortedDictionary<int, int>();
lengthDictionary在键值对中具有值,如下所示:
<1,20>
<2,8>
<3,10>
<4,5>
我想要LINQ查询,它会返回我的新列表,如下所示
<1,20>
<2,20+8=28> // 20 from key 1
<3,28+10=38> // 28 from key 2
<4,38+5=43> // 38 from key 3
结果应该是这样的:
<1,20>
<2,28>
<3,38>
<4,43>
答案 0 :(得分:2)
int tempTotal = 0;
Dictionary<int, int> result = lengthDictionary.ToDictionary(p => p.Key, p =>
{
tempTotal += p.Value;
return tempTotal;
});
注意:未经测试。此外,您可能希望更改投影类型。
编辑:如果您想要一个有序的结果,这是我的原始答案:
int runningTotal = 0;
lengthDictionary.Select(p =>
{
runningTotal += p.Value;
return new {Key = p.Key, Value = runningTotal};
});
答案 1 :(得分:0)
如果您需要查询而不一定是新的排序字典,则可以构建类似的内容。
int runningSum = 0;
var query = (from pair in lengthDictionary
let innerSum = (runningSum += pair.Value)
select new
{
Key = pair.Key,
Value = innerSum
});
// make a new SortedDictionary?
var newDictionary = new SortedDictionary<int, int>(query.ToDictionary(pair => pair.Key, pair => pair.Value));
// display to confirm result
foreach (var pair in newDictionary)
Console.WriteLine("{0}\t{1}", pair.Key, pair.Value);
注意:非LINQ答案可能更简单,特别是如果您想要一个新词典作为输出。
var newDictionary = new SortedDictionary<int, int>();
int runningTotal = 0;
foreach (var pair in lengthDictionary)
{
runningTotal += pair.Value;
newDictionary.Add(pair.Key, runningTotal);
}
答案 2 :(得分:0)
这是我的方法:
SortedDictionary<int, int> dictionary = new SortedDictionary<int, int>()
{
{1, 20},
{2, 8},
{3, 10},
{4, 5}
};
var result = Enumerable
.Range(0, dictionary.Keys.Count)
.Select(i => new
{
Key = dictionary.Keys.Skip(i).First(),
Value = dictionary.Take(i+1).Select(k => k.Value).Sum()
})
.ToDictionary(k => k.Key, v => v.Value);
foreach(var r in result)
{
Console.WriteLine("Key = {0}, Value = {1}", r.Key, r.Value);
}
Console.WriteLine("done");
Console.ReadLine();