简体   繁体   English

使用LINQ填充具有特定数字范围的列表

[英]Populate a list with a specific range of numbers by using LINQ

In order to populate a List<int> with a range of numbers from 1 to n I can use: 为了使用从1到n的数字范围填充List<int> ,我可以使用:

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 UPDATE

Assume I have a method getMonthName(i) that given the integer returns the name of the month. 假设我有一个方法getMonthName(i) ,给定整数返回月份的名称。 Can I populate the list directly with month names somehow by using Enumerable 我可以使用Enumerable以某种方式直接使用月份名称填充列表

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

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 . 如果您提出这类问题,可能需要查看System.Linq.Enumerable的方法。 That's where all this stuff is kept. 这就是保留所有这些东西的地方。 Don't miss ToLookup , Concat (vs Union ), and Repeat . 不要错过ToLookupConcat (vs Union )和Repeat

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM