Yue Wang Yue Wang - 3 months ago 12
C# Question

How to modify object from a lambda expression body used in Linq Extension method?

I want the side effect when using lambda expression with

Select
extension method, something like this:

using System;
using System.Collections.Generic;
using System.Linq;

namespace SyntaxExperiment {

public class Program {
static void Main() {
var list = new List<int>();
var results = new[] { 1, 2, 3 }
.Select(
i => {
list.Add(i);
return i;
}
);
Console.WriteLine(list.Count);
}
}
}


The code above outputs:

0


How is this possible?

Answer

The LINQ code is not actually executing because it's just an IEnumerable<int> that has no reason to execute. You can force it to execute like this:

var results = new[] { 1, 2, 3 }
    .Select(i => {
        list.Add(i);
        return i;
    })
    .ToList();

To put it another way, an enumerable doesn't do anything until you enumerate through it, and ToList, by forcing the data into a collection, causes that enumeration.

Comments