LINQ:点符号与查询表达式 [英] LINQ: Dot Notation vs Query Expression

查看:32
本文介绍了LINQ:点符号与查询表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始使用 LINQ(到目前为止,toXML 和 toSQL).我已经看到有时有两种或多种方法可以实现相同的结果.举这个简单的例子,据我所知,两者都返回完全相同的东西:

I am beginning to use LINQ in general (so far toXML and toSQL). I've seen that sometimes there are two or more ways to achieve the same results. Take this simple example, as far as I understand both return exactly the same thing:

SomeDataContext dc = new SomeDataContext();

var queue = from q in dc.SomeTable
        where q.SomeDate <= DateTime.Now && q.Locked != true
        orderby (q.Priority, q.TimeCreated)
        select q;

var queue2 = dc.SomeTable
        .Where( q => q.SomeDate <= DateTime.Now && q.Locked != true )
        .OrderBy(q => q.Priority)
        .ThenBy(q => q.TimeCreated);

这个想法是有两种方式来表达同一件事;我知道第一种方法有一些局限性,点表示法"更完整,但除此之外,还有其他优点吗?

The idea is that there are two ways to express the same thing; I understand that the first method has some limitations and that the "dot notation" is more complete, but besides that, are there any other advantages?

推荐答案

点"表示法通常称为 Lambda 语法.第一个符号有许多名称,但我通常称之为查询语法.

The "dot" notation is usually called Lambda syntax. The first notation goes by a number of names but I usually call it the query syntax.

我在一个由 10 名开发人员组成的团队中工作,我们详细讨论了我们应该使用哪个作为标准.一般来说,经验丰富(使用 LINQ)的开发人员会迁移到 Lambda 语法,但也有明显的例外.

I work on a team of 10 developers and we argue at length about which we should use as a standard. In general, the more seasoned (with LINQ) developers migrate towards the Lambda syntax but there are significant exceptions.

Lambda 更简洁,但执行多个表连接是一场噩梦.使用查询语法,联接更加清晰.另一方面是有许多 LINQ 操作只存在于 Lambda 语法中:Single()、First()、Count() 等.

Lambda is more concise but performing multiple table joins is a nightmare. Joins are just much cleaner with the query syntax. The flip side is that there are a number of LINQ operations that only exist within the Lambda syntax: Single(), First(), Count() etc.

因此,使用您觉得最舒服的方式,并意识到随着经验的积累,您的偏好可能会发生变化.能够同时阅读两者具有很大的价值,而且在某些情况下,您肯定需要同时使用两者.其他情况会使自己倾向于一种风格而不是另一种风格.最后,它们都被翻译成相同的可执行代码.

So, use what you feel most comfortable with and realize that as you gain experience, your preference will likely change. There is great value in being able to read both and there will certainly be situations where you have to use a little bit of both. Other situations will lend themselve to one style over the other. In the end, it all gets translated into the same executable code.

这篇关于LINQ:点符号与查询表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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