Populate a list with a specific range of numbers by using LINQ

落爺英雄遲暮 提交于 2019-12-03 08:17:21

问题


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


回答1:


Enumerable.Range(1,12).Select(getMonthName);



回答2:


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.




回答3:


For the month names you can use Select():

var months = Enumerable.Range(1,n).Select(getMonthName);


来源:https://stackoverflow.com/questions/9361598/populate-a-list-with-a-specific-range-of-numbers-by-using-linq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!