Lambda表达式 和 Expression

时间:2021-11-25 18:48:48

经常用的Lambda表达式 返回的是  Expression<T> 格式

 public class ActivityService
    {
        private readonly List<Activity> _source = new List<Activity>();

        public ActivityService()
        {
            _source.Add(new Activity() 
            { 
                Id = "5656d551d430520e100fa4f5"  ,
                Name="奥运会"
            });
            _source.Add(new Activity()
            {
                Id = "d702abd8",
                Name = "亚运会"
            });
            _source.Add(new Activity()
            {
                Id = "706b0ba267a9",
                Name = "美洲杯"
            });

            _source.Add(new Activity()
            {
                Id = "47d6",
                Name = "世界杯"
            });
            _source.Add(new Activity()
            {
                Id = "4a8d",
                Name = "大运会"
            }); 
            _source.Add(new Activity()
            {
                Id = "acdb",
                Name = "欧洲杯"
            });
        }

        public Activity GetOne(Expression<Func<Activity, bool>> where)
        {
            var func = where.Compile();
            return _source.FirstOrDefault(o => func(o));

        }
    }

  

  public class Activity
    {
        public string Id { get; set; }
        public string Name { get; set; }

    }

  

调用方式如下:

class Program
    {
        static void Main(string[] args)
        {
            ActivityService service=new ActivityService();
            string id = string.Empty;
            string name = "大运会";

            //表达式不支持语句块
            Expression<Func<Activity, bool>> expression =
                (Activity a) => string.IsNullOrEmpty(id) ? a.Name == name : a.Id == id;

            //如果需要语句块 可以直接使用委托,然后有2种方法 (1)将其封装到Excepression (2)直接使用Lambda表达式
            Func<Activity, bool> func = (a) =>
            {
                if (!string.IsNullOrEmpty(id))
                    return a.Id == id;
                return a.Name == name;
            };
            //expression = (Activity a) => func(a);
            //或者直接在下面使用Lambda
            var activity2 = service.GetOne( (a)=>func(a));

            var activity = service.GetOne(expression);
            Console.Read();
        }
    }