0

In the below example when I donot use .ToList() in the Line - var b = a.SelectMany(x => a.Select(y => { ans.Add(new Tuple<int, int>(x, y)); return false; })).ToList();

The Count of ans is 0

Can someone explain what exactly happening here with and without .ToList();

 public void selectAll()
    {
        var ans = new List<Tuple<int, int>>();
        var a = new List<int>()
        {
            1,2,3
        };
        var b = a.SelectMany(x => a.Select(y => { ans.Add(new Tuple<int, int>(x, y)); return false; })).ToList();
        foreach (var item in ans)
        {
            Console.WriteLine($"{item.Item1},{item.Item2}");
        }
    }
SaiRaj
  • 11
  • 1
  • 2
    1. You are abusing LINQ by calling methods with side effects (`ans.Add`). That is not the intent of LINQ - it is for filtering and querying, not modifications or side effects (except in special rare cases). 2. LINQ uses [deferred execution](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/classification-of-standard-query-operators-by-manner-of-execution) for most operators - that means the query is not processed until instantiated in some way, either by a `foreach` or by a method like `ToList` or `Count` or `First`. – NetMage May 24 '22 at 18:48
  • 1
    Does this answer your question? [What are the benefits of a Deferred Execution in LINQ?](https://stackoverflow.com/questions/7324033/what-are-the-benefits-of-a-deferred-execution-in-linq) – NetMage May 24 '22 at 18:49

1 Answers1

0

Don't use side effects use something like this:

var a = Enumerable.Range(1, 3);
var ans =  a.Select(x => a.Select(y => new Tuple<int, int>(x, y))).SelectMany(z => z);
foreach (var item in ans)
{
    Console.WriteLine($"{item.Item1},{item.Item2}");
}
Wouter
  • 2,540
  • 19
  • 31