Csharp/CSharp Tutorial/LINQ/Lambda

Материал из .Net Framework эксперт
Версия от 12:18, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

A lambda expression can reference the local variables and parameters of the method in which it"s defined.

using System;
delegate int NumericSequence();
class Test {
    static void Main() {
        int seed = 0;
        NumericSequence natural = () => seed++;
        Console.WriteLine(natural());
        Console.WriteLine(natural());
    }
}

A lambda expression has the following BNF form: (parameters) => expression-or-statement-block

using System;
class Test {
    static void Main() {
        Func<int, int> square = x => x * x;
        Console.WriteLine(square(3));     // 9
    }
}

A local variable instantiated within a lambda expression is unique per invocation of the delegate instance.

using System;
delegate int NumericSequence();
class Test {
    static NumericSequence Natural() {
        return () => { int seed = 0; return seed++; };
    }
    static void Main() {
        NumericSequence natural = Natural();
        Console.WriteLine(natural());
        Console.WriteLine(natural());
    }
}

Concise Lambda Expression

using System;
using System.ruponentModel;
    class MainClass
    {
        static void Main()
        {
            Func<string, int> returnLength;
            returnLength = (text => text.Length);
            Console.WriteLine(returnLength("Hello"));
        }
    }

If your query"s lambda expressions reference local variables, these variables are subject to outer variable semantics.

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

Lambda expression used to declare a delegate

using System;
using System.Linq;
using System.Linq.Expressions;
class Program {
    static void Main(string[] args) {
        Func<int, bool> isOddDelegate = i => (i & 1) == 1;
        for (int i = 0; i < 10; i++) {
            if (isOddDelegate(i))
                Console.WriteLine(i + " is odd");
            else
                Console.WriteLine(i + " is even");
        }
    }
}

Lambda expression used to declare an expression tree

using System;
using System.Linq;
using System.Linq.Expressions;
class Program {
    static void Main(string[] args) {
        Expression<Func<int, bool>> isOddExpression = i => (i & 1) == 1;
        ParameterExpression param = Expression.Parameter(typeof(int), "i");
        Expression<Func<int, bool>> isOdd =
            Expression.Lambda<Func<int, bool>>(
            Expression.Equal(
              Expression.And(
                param,
                Expression.Constant(1, typeof(int))),
              Expression.Constant(1, typeof(int))),
            new ParameterExpression[] { param });
        Func<int, bool> isOddCompiledExpression = isOddExpression.rupile();
        for (int i = 0; i < 10; i++) {
            if (isOddCompiledExpression(i))
                Console.WriteLine(i + " is odd");
            else
                Console.WriteLine(i + " is even");
        }
    }
}

List Sort With Lambda Expression

using System.Text;
using System.Xml.Linq;
using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Linq;
    class Product
    {
        public string Name { get; private set; }
        public decimal Price { get; private set; }
        public Product(string name, decimal price)
        {
            Name = name;
            Price = price;
        }
        Product()
        {
        }
        public static List<Product> GetSampleProducts()
        {
            return new List<Product>
            {
                new Product { Name="C", Price = 9.99m },
                new Product { Name="A", Price=14.99m },
                new Product { Name="F", Price=13.99m },
                new Product { Name="S", Price=10.99m}
            };
        }
        public override string ToString()
        {
            return string.Format("{0}: {1}", Name, Price);
        }
    }
    class ListSortWithLambdaExpression
    {
        static void Main()
        {
            List<Product> products = Product.GetSampleProducts();
            products.Sort(
                (first, second) => first.Name.rupareTo(second.Name)
            );
            foreach (Product product in products)
            {
                Console.WriteLine(product);
            }
        }
    }

return a lambda function

using System;
delegate int NumericSequence();
class Test {
    static NumericSequence Natural() {
        int seed = 0;
        return () => seed++;
    }
    static void Main() {
        NumericSequence natural = Natural();
        Console.WriteLine(natural());
        Console.WriteLine(natural());
    }
}

square is assigned the lambda expression x = > x * x:

using System;
delegate int Transformer(int i);
class Test {
    static void Main() {
        Transformer square = x => x * x;
        Console.WriteLine(square(3));    // 9
    }
}

Using Lambda Expressions with Find method

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Xml.Linq;
    class Program
    {
        static void Main(string[] args)
        {
            // 
            List<string> myList2 = new List<string>();
            myList2.Add("A");
            myList2.Add("B");
            myList2.Add("C");
            myList2.Add("D");
            string vanilla2 = myList2.Find((string icecreamname) => icecreamname.Equals("B"));
            Console.WriteLine(vanilla2);
        }
      
    }