有没有办法使用 LINQ 表达式填充集合?

发布于 2024-08-17 10:26:38 字数 897 浏览 2 评论 0原文

LINQ 的优点之一是它允许您获取与集合相关的信息,而无需手动编写代码来迭代集合。 有没有办法使用 LINQ 填充集合,从而避免编写循环?


例如,假设我有以下代码,它可以处理从 1 到 10 的数字范围:

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}\tSum of Odds is {1}\tAverage is {2}", 
        intSum, intSumOdds, intAverage);
}

LINQ 已经取代了检索有关数据的信息所需的for 循环。我很好奇 LINQ 是否可以用来替换填充数据的for循环。有没有办法用LINQ来替换下面两行代码?

    for (int i = 1; i <= 10; i++)
        intList.Add(i);

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?


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}\tSum of Odds is {1}\tAverage is {2}", 
        intSum, intSumOdds, intAverage);
}

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);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

静谧 2024-08-24 10:26:39

正如其他人所说,您可以使用 Enumerable.Range(int, int) 生成以 IEnumerable 返回的整数序列。

虽然您可以通过已经建议的各种方式将结果转换为 List,但只有在您确实需要 List 时才应该这样做>。

在这种情况下,没有必要这样做。您的函数可以重写如下:

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 时,所有值必须立即保存在内存中。

As the others have said, you can use Enumerable.Range(int, int) to generate a sequence of integers returned as IEnumerable<int>.

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();

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.

高冷爸爸 2024-08-24 10:26:39

您不会使用 LINQ 填充现有列表;您将创建一个 Enumerable ,然后将其转换为列表。在这种情况下,很简单

IList<int> intList = Enumerable.Range(1, 10).ToList();

You wouldn't fill an existing list with LINQ; you'd create an Enumerable and then convert it to a list. In this case, it's as simple as

IList<int> intList = Enumerable.Range(1, 10).ToList();
北方的韩爷 2024-08-24 10:26:39

我认为您在特定情况下寻找的是Enumerable.Range()。从那里,如果您愿意,您可以使用 Where 等过滤列表。例如,如果我想要 2 的幂低于 100 的所有数字,我会执行类似 Enumerable.Range(1,100).Where(i => i * i < 100) 的操作。这在像 Haskell 这样的函数式语言中很常见,类似的东西是这样的: filter (\i -> i * i < 100) [1..100]

替换函数的具体示例:

Enumerable.Range(1,10).Where(x => x%2 == 1).Sum();
//add separate sum and averages here

I think what you're looking for in the specific case is Enumerable.Range(). From there, if you want to you can filter the list by using Wheres and such. For instance, if i wanted all the numbers from whose power of two is below 100 i'd do something like Enumerable.Range(1,100).Where(i => i * i < 100). This is very common in functional languages like Haskell where something similar is this: filter (\i -> i * i < 100) [1..100]

A specific example to replace your function:

Enumerable.Range(1,10).Where(x => x%2 == 1).Sum();
//add separate sum and averages here
勿忘初心 2024-08-24 10:26:39

List 有一个构造函数,该构造函数采用 IEnumerable 作为参数。您可以使用 Enumerable.Range 生成数字。

List<int> values = new List<int>(Enumerable.Range(1, 10));

如果要将值添加到先前构造的 List 中,可以以相同的方式使用 List.AddRange

values.AddRange(Enumerable.Range(1, 10));

List<T> has a constructor that takes an IEnumerable<T> as a parameter. You can use Enumerable.Range to generate the numbers.

List<int> values = new List<int>(Enumerable.Range(1, 10));

If you want to add the values to a previously constructed List<T>, you can use List<T>.AddRange in the same way:

values.AddRange(Enumerable.Range(1, 10));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文