Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate List<string> with the same value with LINQ

Tags:

I want to populate a List<string> with the same string value for a specified number of times.

In straight C# it is:

List<string> myList = new List<string>(); for (int i = 0; i < 50; ++i) {     myList.Add("myString"); } 

Is it possible to do this with LINQ?

like image 619
Simon Linder Avatar asked Jun 05 '13 08:06

Simon Linder


1 Answers

Yes, use Enumerable.Repeat:

var myList = Enumerable.Repeat("myString", 50).ToList(); 

or this:

var myList = new List<string>(Enumerable.Repeat("myString", 50)); 

If you have an existing list you want to add those elements to, use this:

myList.AddRange(Enumerable.Repeat("myString", 50)); 

Note that this is not exactly LINQ per se, but it uses the extension methods that was added together with LINQ to support the new syntax. With just LINQ (ie. the "from ... select" syntax), it's a bit different, then I would do this:

var myList = (from idx in Enumerable.Range(0, 50) select "myString").ToList(); 

However, I wouldn't actually do this, I would instead use the methods of Enumerable.

Also, if you want to create different strings, depending on whether it is the first, second, third, etc. item you're adding, you can use Enumerable.Range instead:

var myList = Enumerable.Range(0, 50).Select(idx => "myString#" + idx).ToList(); 

Will create a list with the strings myString#0, myString#1, myString#2, ...

like image 157
Lasse V. Karlsen Avatar answered Sep 18 '22 15:09

Lasse V. Karlsen