1

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()
AleksP
  • 1,244
  • 2
  • 12
  • 18
  • 2
    Dictionaries are unordered. `FirstOrDefault()` will not work correctly here. – SLaks Dec 03 '14 at 15:25
  • Can you expand your answer and tell us why you need to do this? It'll help us help you – Binary Worrier Dec 03 '14 at 15:25
  • Dictionaries don't have an order. If you used an `OrderedDictionary` then a `foreach` may be cleaner since you'll need to keep track of the "last" key. – D Stanley Dec 03 '14 at 15:26
  • possible duplicate of [how do access previous item in list using linQ?](http://stackoverflow.com/questions/4460106/how-do-access-previous-item-in-list-using-linq) – Daniel Edholm Ignat Dec 03 '14 at 15:26

2 Answers2

3

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)
Vsevolod Goloviznin
  • 12,074
  • 1
  • 49
  • 50
  • 1
    And how would you apply that to the problem? `dict[index]` will NOT select the "nth" item; it will return the value where `index` is the key. – D Stanley Dec 03 '14 at 15:28
  • but how access to key because dict[index].(value only) - my dictionary contain for ex: 23,10.00; 150,56.7; and i need to getting exactly key – AleksP Dec 03 '14 at 15:34
  • @AleksP I've updated the answer. In fact I think it would be easier done with just an ordinary `for` loop – Vsevolod Goloviznin Dec 03 '14 at 15:36
  • @AleksP You still need to deal with the fact that a `Dictionary` isn't necessarily ordered by its key. – D Stanley Dec 03 '14 at 15:40
0

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.

D Stanley
  • 149,601
  • 11
  • 178
  • 240