Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List.add using Linq

Tags:

c#

lambda

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. I am keen to know what are the scenarios the LINQ or lambda expressions useful and should be used

For this code: Can I use Linq or lambda expressions

List<int> abundantNumbers = new List<int>();
for (int i = 0; i < 28888; i++)
     {
      if (i < pta.SumOfDivisors(i))
         {
          abundantNumbers.Add(i);
          }
     }
like image 356
Ajax3.14 Avatar asked Jul 21 '26 18:07

Ajax3.14


1 Answers

Yes, you can absolutely use LINQ in your example:

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);
like image 70
Jon Skeet Avatar answered Jul 23 '26 06:07

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!