Yue Wang Yue Wang - 7 months ago 27
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

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 }
i => {
return i;

The code above outputs:


How is this possible?


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 => {
        return i;

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.