1

I'm need to call function from ForEach in Linq, and I need to send a string parameter and the Index from the ForEach

List<string> listString= new List<string>();

listString.ForEach((str, i) => { Func(str, i) , i++});

private ResponseBase Func(string s,int i)
{
Christos
  • 50,311
  • 8
  • 62
  • 97
Ayal
  • 113
  • 1
  • 10

3 Answers3

4

You could try something like this:

var responses = listString.Select((value, index) => Func(value, index)).ToList();

The above for each item in listString would call the method you have defined. The results of all calls would be stored in a list and you could access them by using the corresponding index.

Christos
  • 50,311
  • 8
  • 62
  • 97
1

I'm a big fan of LINQ. Really.

But in this cases, when you are accessing an already existing List, I would go for an old fashioned for loop.

for(var i = 0; i < listString.Count; i++)
    Func(listString[i], i);

It's not longer, it's far more efficient (it's probably not a problem, but let's remember this), and it just gets the job done.

A. Chiesa
  • 5,367
  • 1
  • 21
  • 43
1

You can introduce a variable and then increment it:

List<String> values = new List<String>();
int indexTracker = 0;
values.ForEach(x=> { Func(x, indexTracker++); });

Or you can write the following extension method:

public static void ForEach<T>(this List<T> input, Action<T, int> action)
{
    for(int i = 0; i < input.Count; i++)
    {
        action(input[i], i);
    }
}

and then use it like

values.ForEach((x,i)=> Func(x, i)); 
Transcendent
  • 4,866
  • 4
  • 19
  • 46