是 Linq 还是 Lambda? [英] Is it Linq or Lambda?

查看:40
本文介绍了是 Linq 还是 Lambda?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是 Linq:

var _Results = from item in _List其中 item.Value == 1选择物品;

我知道这是 Lambda:

var _Results = _List.Where(x => x.Value == 1);

<块引用>

编者注:以上不仅仅是Lambda,它是Linq使用的方法语法",其谓词是一个 Lambda.要清楚,以上两个样本是 Linq(我原来的帖子不正确,但我留下了错误以说明引发问题的混乱).

但 Linq 是 Lambda 的子集还是什么?

为什么有两个看似相同的技术?

选择其中一个是否有技术原因?

解决方案

这是 LINQ(使用查询语法):

var _Results = from item in _List其中 item.Value == 1选择物品;

这也是 LINQ(使用方法语法):

var _Results = _List.Where(x => x.Value == 1);

有趣的是,这两种风格最终会生成完全相同的代码.编译器通过允许您以您喜欢的方式表达您的愿望来为您提供服务.

而且这个是一个lambda:

x =>x.Value == 1

当您选择使用方法语法时,几乎总是在 lambda 表达式周围看到 LINQ.但是 LINQlambdas 是两个完全不同的东西,两者都可以单独使用.

更新:正如 svick 正确指出的那样,具有查询语法的 LINQ 使用 lambda 表达式实现(如前所述,编译器允许您编写查询语法,但是有效地将其转换为背后的方法语法).这只是基于这样一个事实,即两种风格完全相同并且行为方式相同(例如 lambda 表达式可能导致 闭包 待创建).

I know that this is Linq:

var _Results = from item in _List
                where item.Value == 1
                select item;

And I know this is Lambda:

var _Results = _List.Where(x => x.Value == 1);

Editor's note: the above is not merely Lambda, it is Linq using the "Method Syntax" whose predicate is a Lambda. To be clear, both of the above samples are Linq (my original post was incorrect, but I left the error to illustrate the confusion prompting the question).

But is Linq a subset of Lambda or what?

Why are there two seemingly identical techs?

Is there a technical reason to choose one over the other?

解决方案

This is LINQ (using query syntax):

var _Results = from item in _List
                where item.Value == 1
                select item;

This is also LINQ (using method syntax):

var _Results = _List.Where(x => x.Value == 1);

It's interesting to note that both of these flavors will end up producing the exact same code. The compiler offers you a service by allowing you to express your wishes in the manner that you prefer.

And this is a lambda:

x => x.Value == 1

When you choose to use method syntax, LINQ is almost always seen around lambda expressions. But LINQ and lambdas are two totally different things, both of which can be used by themselves.

Update: As svick rightly points out, LINQ with query syntax is also implemented using lambda expressions (as mentioned earlier, the compiler allows you to write in query syntax but effectively transforms it to method syntax behind your back). This is just piling on the fact that both flavors are totally equivalent and will behave the same way (e.g. lambda expressions may cause closures to be created).

这篇关于是 Linq 还是 Lambda?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆