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?
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
, ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With