user11814338
user11814338

Reputation:

how to access the next item in the list in lambda expressions

I am creating a simple query (if this is even the term of using LINQ) that takes each number in the list, added is to the index, and then from the new list I want to divide the value with the highest index with the value that has the highest index - 1 and then do that same action on all the indexes in the pairs (index val, index val-1) so the result will be a list half a size of the original list, and then pick the highest result from the new list.

 var lst = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

   var fianle = lst
               .Select((value, i) => new { i, value })
               .Select(item =>
          item.value + item.i)
             .Select((x , how to accse the previos item? ) => x/previositem)
            .Max(x => x);

so i want to know

  1. how to loop backward using lambda expressions
  2. how to access the previous item in the list using lambda expressions

thank you in advance!

Upvotes: 1

Views: 929

Answers (1)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62498

You can have a property in your anonymous object to hold previous one:

var listWithPrevious = lst
               .Select((value, i) => 
                          new { 
                                Index = i,
                                Value = value,
                                Previous = lst.ElementAtOrDefault(i + 1) 
                              });

and then use the collection above to do what ever is required.

You can modify your code to be like:

var fianle = lst
           .Select((value, i) => 
                         new { 
                                Index = i,
                                Value = value,
                                Previous = lst.ElementAtOrDefault(i + 1) 
                              })
           .Select(item =>
      item.value + item.i)
         .Select((x , Previous ) => x/Previous)
        .Max(x => x);

Upvotes: 1

Related Questions