Create lambda expressions which referencing local variables in CSharp

Description

The following code shows how to create lambda expressions which referencing local variables.

Example


  //from w w  w . j  av  a2  s  .  c o m

using System;
using System.Collections.Generic;
using System.Linq;
public class MainClass {
    public static void Main() {

        int[] numbers = { 1, 2 };

        int factor = 10;
        IEnumerable<int> query = numbers.Select(n => n * factor);

        factor = 20;
        foreach (int n in query) Console.Write(n + "|");   
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor