5

I have an array of strings like this:

test[1] = "AA";
test[2] = "BB";

I like to do things in good ways. Now I need to iterate through the array so it looks like this:

1. "AA"
2. "BB"
etc ..

I think I can do this with a for loop and index but I am wondering if I can also do it with LINQ.

4
  • Without knowing what you actually want to do its hard to suggest a solution. Commented Jul 13, 2011 at 7:32
  • 1
    Nice answer from @polishchuk. Why would you jump into LINQ for something as simple as this? Using LINQ will generate a new IEnumerable - so you will have two instances of your list floating around, which becomes problematic if you are dealing with a very large array. LINQ is great, but it isn't the solution to every little iteration problem, there is still a place for a simple for loop. Commented Jul 13, 2011 at 7:52
  • If I didn't use LINQ then can I do it really easy with another way? Commented Jul 13, 2011 at 7:55
  • Simple for loop: for (int i = 0; i < arr.Length; i++) arr[i] = string.Format("{0}. {1}", i+1, arr[i]);. It's all good if you are simply learning how to use LINQ, but sometimes there is nothing wrong with the basics... Commented Jul 13, 2011 at 8:13

1 Answer 1

20

Prior to C# 6.0:

var result = test.Select((s, i) => string.Format("{0}. {1}", i + 1, s));

Starting from C# 6.0 you can use interpolated strings:

var result = test.Select((s, i) => $"{i + 1}. {s}");
Sign up to request clarification or add additional context in comments.

3 Comments

I get a message "does not contain a definition for 'Select' and no extension method 'Select' accepting a first argument of type". If I don't use LINQ how I could I do this?
You are missing using System.Linq;
@polishchuk Nice. The only thing I miss is ++i instead of i + 1 ;-)

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.