How to get a previous element in select(foreach) some like this dic[index -1].Key
new Dictionary<int, double>();
dic.Select(x => x.Value*(x.Equals(dic.FirstOrDefault()) ? x.Key : //x.Key - dic[index -1].Key//)).Sum()
How to get a previous element in select(foreach) some like this dic[index -1].Key
new Dictionary<int, double>();
dic.Select(x => x.Value*(x.Equals(dic.FirstOrDefault()) ? x.Key : //x.Key - dic[index -1].Key//)).Sum()
Select
method provides an index as a second parameter.
dic.Select((x, index) => dict[index])
If you want to select an element at previous index you can use ElementAt
dic.Select((x, index) => dic.ElementAt(index).Key)
If you use an OrderedDictionary
then it may be faster to use a straight foreach
:
double sum = 0.0;
int prev = 0;
foreach(var kvp in dic)
{
sum += kvp.Value * (kvp.Key - prev);
prev = kvp.Key;
}
In any case, I would first come up with something that works and then refactor it if you can make it better. And "better" may not be using Linq; a convoluted Linq query that's hard to understand and debug is worse than a clean, efficient loop in most cases.