现在的位置: 首页 > 综合 > 正文

c#3.0新特性使用lambda表达式创建表达式树

2013年09月05日 ⁄ 综合 ⁄ 共 4421字 ⁄ 字号 评论关闭

c#3.0新特性使用lambda表达式创建表达式树
2009年8月18日 云飞扬 发表评论 阅读评论
-
c#3.0新特性使用lambda表达式创建表达式树

题外话:这空间访问速度真慢,在我发布文章的时候,感觉花费九牛二虎之力。几篇已经准备好的文章花费1个多小时发布。

Using Lambda Expressions to Create Expression Trees 使用lambda表达式创建表达式树

1.使用前引入类

using System.Linq.Expressions;

2.加入main()

            Expression<Func<int, bool>> filter = n => (n * 3) < 5;

            BinaryExpression lt = (BinaryExpression)filter.Body;//{((n * 3) < 5)}
            BinaryExpression mult = (BinaryExpression)lt.Left;//{(n * 3)}
            ParameterExpression en = (ParameterExpression)mult.Left;// {(n)}
            ConstantExpression three = (ConstantExpression)mult.Right;//{(3)}
            ConstantExpression five = (ConstantExpression)lt.Right;//{(5)}

            Console.WriteLine("({0} ({1} {2} {3}) {4})", lt.NodeType,
                      mult.NodeType, en.Name, three.Value, five.Value);//<LessThan <Multiply n 3>>
            Console.ReadKey();

完整的程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
namespace NewLanguageFeatures
{
    public delegate bool KeyValueFilter<K, V>(K key, V value);
  
    public static class Extensions
    {
        public static List<K> FilterBy<K, V>(
        this Dictionary<K, V> items,
        KeyValueFilter<K, V> filter)
        {
            var result = new List<K>();

            foreach (KeyValuePair<K, V> element in items)
            {
                if (filter(element.Key, element.Value))
                    result.Add(element.Key);
            }
            return result;
        }
      
        public static List<T> Append<T>(this List<T> a, List<T> b)
        {
            var newList = new List<T>(a);
            newList.AddRange(b);
            return newList;
        }
      
        public static bool Compare(this Customer customer1, Customer customer2)
        {
            if (customer1.CustomerId == customer2.CustomerId &&
                customer1.Name == customer2.Name &&
                customer1.City == customer2.City)
            {
                return true;
            }

            return false;
        }
    }

    public class Customer
    {
        public int CustomerId { get; private set; }

        public string Name { get; set; }
        public string City { get; set; }

        public Customer(int Id)
        {
            CustomerId = Id;
        }

        public override string ToString()
        {
            return Name + "/t" + City + "/t" + CustomerId;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Expression<Func<int, bool>> filter = n => (n * 3) < 5;

            BinaryExpression lt = (BinaryExpression)filter.Body;//{((n * 3) < 5)}
            BinaryExpression mult = (BinaryExpression)lt.Left;//{(n * 3)}
            ParameterExpression en = (ParameterExpression)mult.Left;// {(n)}
            ConstantExpression three = (ConstantExpression)mult.Right;//{(3)}
            ConstantExpression five = (ConstantExpression)lt.Right;//{(5)}

            Console.WriteLine("({0} ({1} {2} {3}) {4})", lt.NodeType,
                      mult.NodeType, en.Name, three.Value, five.Value);//<LessThan <Multiply n 3>>
            Console.ReadKey();
//去掉注释的可以调试一下
            ////------2----------------------------------------
            //Func<int, int> addOne = n => n + 1;
            //Console.WriteLine("Result: {0}", addOne(5));

            ////---------------------------------------3-------------

            //Func<int, int> addOne = n => n + 1;
            //Console.WriteLine("Result: {0}", addOne(5));

            //Expression<Func<int, int>> addOneExpression = n => n + 1;

            //var addOneFunc = addOneExpression.Compile();
            //Console.WriteLine("Result: {0}", addOneFunc(5));
        }

        public static List<Customer> FindCustomersByCity(
            List<Customer> customers,
            string city)
        {
            return customers.FindAll(c => c.City == city);
        }

        static List<Customer> CreateCustomers()
        {
            return new List<Customer>
                {
                    new Customer(1) { Name = "Alex Roland",             City = "Berlin"    },
                    new Customer(2) { Name = "Oliver Cox",              City = "Marseille" },
                    new Customer(3) { Name = "Maurice Taylor",          City = "London"    },
                    new Customer(4) { Name = "Phil Gibbins",            City = "London"    },
                    new Customer(5) { Name = "Tony Madigan",            City = "Torino"    },
                    new Customer(6) { Name = "Elizabeth A. Andersen",   City = "Portland"  },
                    new Customer(7) { Name = "Justin Thorp",            City = "London"    },
                    new Customer(8) { Name = "Bryn Paul Dunton",        City = "Portland"  }
                };
        }     
    }
}

本文来自: 本站内容欢迎转载,但是禁止去掉本文链接(转载无妨,去掉链接可耻!):http://www.ajaxcn.net/archives/186

抱歉!评论已关闭.