Populate a list with a specific range of numbers b

2020-05-23 02:10发布

In order to populate a List<int> with a range of numbers from 1 to n I can use:

for (i=1; i<=n; i++)
{
   myList.Add(i);
}

Is there any way to achieve the same result by using LINQ inline expressions?

UPDATE

Assume I have a method getMonthName(i) that given the integer returns the name of the month. Can I populate the list directly with month names somehow by using Enumerable

标签: c# linq list range
3条回答
劳资没心,怎么记你
2楼-- · 2020-05-23 02:58

For the month names you can use Select():

var months = Enumerable.Range(1,n).Select(getMonthName);
查看更多
Fickle 薄情
3楼-- · 2020-05-23 02:59

You want to use Enumerable.Range.

myList.AddRange(Enumerable.Range(1, n));

Or

myList = Enumerable.Range(1, n).ToList();

If you're asking this kind of question, you might want to look over the methods of System.Linq.Enumerable. That's where all this stuff is kept. Don't miss ToLookup, Concat (vs Union), and Repeat.

查看更多
叛逆
4楼-- · 2020-05-23 03:02
Enumerable.Range(1,12).Select(getMonthName);
查看更多
登录 后发表回答