简体   繁体   English

List.add使用Linq

[英]List.add using Linq

I have read couple of articles on Linq and Func<> and understood simple examples but I cannot able to use them in day to day programming. 我已经阅读了几篇关于Linq和Func <>的文章并理解了简单的例子,但我无法在日常编程中使用它们。 I am keen to know what are the scenarios the LINQ or lambda expressions useful and should be used 我很想知道LINQ或lambda表达式有用和应该使用的场景是什么

For this code: Can I use Linq or lambda expressions 对于此代码:我可以使用Linq或lambda表达式

List<int> abundantNumbers = new List<int>();
for (int i = 0; i < 28888; i++)
     {
      if (i < pta.SumOfDivisors(i))
         {
          abundantNumbers.Add(i);
          }
     }

Yes, you can absolutely use LINQ in your example: 是的,你可以在你的例子中绝对使用LINQ:

var abundantNumbers = Enumerable.Range(0, 28888)
                                .Where(i => i < pta.SumOfDivisors(i))
                                .ToList();

Note that it's important that you didn't just post code which added to list - you posted code which showed that the list was empty to start with. 请注意,重要的是你不要只发布添加到列表中的代码 - 你发布的代码显示列表是空的开始。 In other words, you're creating a list. 换句话说,您正在创建一个列表。 If you'd merely had code which added to an existing list, I'd have used something like: 如果您只是将代码添加到现有列表中,我会使用以下内容:

var query = Enumerable.Range(0, 28888).Where(i => i < pta.SumOfDivisors(i));
abundantNumbers.AddRange(query);

If you want to do it with the LINQ notation, it would go like this: 如果你想用LINQ表示法做,它会是这样的:

var abundantNumbers = (from i in Enumerable.Range(0, 28888)
                       where i < pta.SumOfDivisors(i)
                       select i)
                      .ToList();

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

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