SortedDictionary<int, string> typeDictionary = new SortedDictionary<int, string>();
SortedDictionary<int, int> lengthDictionary = new SortedDictionary<int, int>();
lengthDictionary has values in key value pair as follows:
<1,20>
<2,8>
<3,10>
<4,5>
i want LINQ query which will return me new list like as follows
<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
Result should like this:
<1,20>
<2,28>
<3,38>
<4,43>
int tempTotal = 0;
Dictionary<int, int> result = lengthDictionary.ToDictionary(p => p.Key, p =>
{
tempTotal += p.Value;
return tempTotal;
});
NOTE: untested. Also, you might want to change what the projected type is.
Edit: Here is my original answer if you want an ordered result:
int runningTotal = 0;
lengthDictionary.Select(p =>
{
runningTotal += p.Value;
return new {Key = p.Key, Value = runningTotal};
});
If you need a query and not necessarily a new sorted dictionary, you can construct something like this.
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);
Note: A non-LINQ answer might arguably be simpler, particularly if you want a new dictionary as an output.
var newDictionary = new SortedDictionary<int, int>();
int runningTotal = 0;
foreach (var pair in lengthDictionary)
{
runningTotal += pair.Value;
newDictionary.Add(pair.Key, runningTotal);
}
Here's my approach:
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.