davioooh
davioooh

Reputation: 24706

How to get array indexes using lambda expression

I was trying to create a string joining elements of an integer array:

string.Join(", ", integerArray.Select(p => p.ToString()).ToArray())

This way I get something like this: 1, 2, 3, 4.

Now I'd like to print, for each element the index of the corresponding position in the array, something like this: {0} 1, {1} 2, {2} 3, {3} 4.

Don't care about format. What I'm wondering is how can I get array index for each selected element in my lambda expression?

Upvotes: 0

Views: 4224

Answers (2)

Steve
Steve

Reputation: 216313

The same as Stanley, just with the curly braces

int[] integerArray = {1,2,3,4,5};
string result = string.Join(", ", integerArray.Select((p, i) => string.Format("{{{0}}} {1}", i, p.ToString())).ToArray());
Console.WriteLine(result);

Upvotes: 2

D Stanley
D Stanley

Reputation: 152596

Select has an overload that takes the index as an input to the lambda:

string.Join(", ", integerArray.Select((p, i) => string.Format("[{0}] {1}",i,p)).ToArray());

Note that I use [] instead of {} just to avoid the ugliness of using curly brackets in string.Format. If you really want curly brackets you could do:

string.Join(", ", integerArray.Select((p, i) => string.Format("{{{0}}} {1}",i,p)).ToArray())

Upvotes: 4

Related Questions