问题描述
LINQ 的一大优点是允许您获取与集合相关的信息,而无需手动编写代码来遍历集合.有没有办法使用 LINQ 填充集合,从而避免编写循环?
One of the great things about LINQ is that allows you to get information that's related to a collection without having to manually write code to iterate through the collection. Is there a way to use LINQ to populate a collection, thus avoiding the need to write a loop?
例如,假设我有以下代码,它适用于从 1 到 10 的数字范围:
For example, let's say I have the following code which works with a range of numbers from one to ten:
public static void LinqTest()
{
List<int> intList = new List<int>();
for (int i = 1; i <= 10; i++) // <==== I'm having to use a for loop
intList.Add(i); // here to populate the List.
int intSum = intList.Sum();
int intSumOdds = intList.Where(x => x % 2 == 1).Sum();
double intAverage = intList.Average();
Console.WriteLine("Sum is {0} Sum of Odds is {1} Average is {2}",
intSum, intSumOdds, intAverage);
}
LINQ 已经替换了 检索 数据信息所需的 for
循环.我很好奇 LINQ 是否可以用来替换 填充 数据的 for
循环.有没有办法用LINQ来代替下面两行代码?
LINQ is already replacing the for
loops that would be required to retrieve information about the data. I'm curious as if LINQ could be used to replace the for
loop that populates data. Is there a way to use LINQ to replace the following two lines of code?
for (int i = 1; i <= 10; i++)
intList.Add(i);
推荐答案
正如其他人所说,您可以使用 Enumerable.Range(int, int)
生成返回为 <代码>IEnumerable
As the others have said, you can use Enumerable.Range(int, int)
to generate a sequence of integers returned as IEnumerable<int>
.
虽然您可以通过已经建议的各种方式将结果转换为 List<int>
,但只有在您确实需要 List<T> 时才应该这样做.代码>.
And while you can convert the result to a List<int>
in the various ways that have been suggested already, you should only do that if you actually need a List<T>
.
在这种情况下,没有必要这样做.你的函数可以改写如下:
In this case, there is no need to do so. Your function could be rewritten as follows:
IEnumerable<int> intList = Enumerable.Range(1, 10);
int intSum = intList.Sum();
int intSumOdds = intList.Where(x => x % 2 == 1).Sum();
double intAverage = intList.Average();
这更有效,因为 Enumerable.Range
返回的序列是在枚举时延迟"生成的.另一方面,当序列转换为 List
时,所有值必须同时保存在内存中.
This is more efficient since the sequence returned by Enumerable.Range
is generated "lazily" as it is enumerated. On the other hand, when the sequence is converted to a List<int>
then all of the values must be held in memory at once.
这篇关于有没有办法使用 LINQ 表达式填充集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!