5

How can I quickly create a string list with numbered strings?

Right now I'm using:

var str = new List<string>();

for (int i = 1; i <= 10; i++)
{
    str.Add("This is string number " + i);
}

This works, however I wonder if there's a quicker way to initialize such a string list, maybe in one or two lines?

2
  • 2
    By "quicker" do you mean "less typing" or "runs faster"? Commented Feb 14, 2013 at 16:18
  • I actually meant less typing. Speed is not an issue. Commented Feb 14, 2013 at 16:22

2 Answers 2

5

You could use LINQ:

Enumerable.Range(1, 10).Select(i => "This is string number " + i).ToList();
Sign up to request clarification or add additional context in comments.

3 Comments

Wow, 14 whole seconds faster :)
Awesome... thank you, I had something like this in mind but I'm not good with LINQ :)
@MartinSvensson - LINQ is simple n amazing, just check it out, you will be better!
3
var str = Enumerable.Range(1, 10).Select(i => "This is string number " + i).ToList();

1 Comment

For completeness: You can also do: var items = (from number in Enumerable.Range(1, 10) select "This is string number " + number).ToList();

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.