Lambda表达式 和 Expression<T>
经常用的Lambda表达式 返回的是 Expression<T> 格式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | 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)); } } |
1 2 3 4 5 6 | public class Activity { public string Id { get ; set ; } public string Name { get ; set ; } } |
调用方式如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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(); } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步