0

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?

0

2 Answers 2

4

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())
Sign up to request clarification or add additional context in comments.

Comments

2

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);

2 Comments

Note that you need three braces instead of two otherwise you'll get {0} for each item.
Right, fixed now, I have already upvoted your answer, reccomending to the OP to accept yours

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.