C# 使用 LINQ 使用特定范围的数字填充列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9361598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:01:53  来源:igfitidea点击:

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

c#linqlistrange

提问by CiccioMiami

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

为了List<int>用从1 到 n的数字范围填充 a ,我可以使用:

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

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

有没有办法通过使用 LINQ 内联表达式获得相同的结果?

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

假设我有一个getMonthName(i)给定整数返回月份名称的方法。我可以使用 Enumerable 以某种方式直接用月份名称填充列表吗

采纳答案by rasmusvhansen

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

回答by Amy B

You want to use Enumerable.Range.

您想使用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.

如果您问此类问题,您可能需要查看System.Linq.Enumerable的方法。这就是保存所有这些东西的地方。不要错过ToLookup, Concat(vs Union), 和Repeat

回答by AlanT

For the month names you can use Select():

对于月份名称,您可以使用Select()

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