What is the difference when converting the Linq result to ToList() and when not converting it toList

24 Views Asked by At

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}");
        }
    }
1

There are 1 best solutions below

0
Wouter On

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