Does LINQ allow you to simplify this construct?
I have a list List<string> MyValues = new List<string>{};
. In my program, I need to hard-code the following:
MyValues.Add(MyFunc(1)); MyValues.Add(MyFunc(2)); ... MyValues.Add(MyFunc(20));
Definitely I can do this in a for-loop. But my guess is that a LINQ should be built that allows you to populate a list with one simple construct, replacing that loop.
Can anyone suggest a LINQ construct that would populate my list?
Thank you so much!
source to share
This can be simplified using Enumerable.Range
:
List<string> myValues = Enumerable.Range(1, 20).Select(MyFunc).ToList();
source to share
Yes, you can use Enumerable.Range
to generate all the numbers together with Select
to do the conversion; and use AddRange
to add all items to your list.
MyValues.AddRange(Enumerable.Range(1, 20).Select(i => MyFunc(i)));
source to share