背景:在接下来的一个月里,我将做三次关于LINQ的演讲,或者至少将LINQ包含在c#的上下文中。我想知道哪些话题值得花相当多的精力,这取决于人们可能很难理解哪些话题,或者他们可能有错误的印象。我不会具体讨论LINQ to SQL或实体框架,只是作为如何使用表达式树(通常是IQueryable)远程执行查询的示例。

那么,你发现LINQ有什么难的地方吗?在误解方面你看到了什么?例子可能是以下任何一个,但请不要限制自己!

c#编译器如何处理查询表达式 Lambda表达式 表达式树 扩展方法 匿名类型 这个IQueryable 延迟执行与立即执行 流与缓冲执行(例如,OrderBy被延迟但被缓冲) 隐式类型局部变量 读取复杂的泛型签名(例如Enumerable.Join)


当前回答

我打赌几乎有人知道:你可以在linq查询中使用内联if。就像这样:

var result = from foo in bars where (
    ((foo.baz != null) ? foo.baz : false) &&
    foo.blah == "this")
    select foo;

我猜你也可以插入,尽管我还没试过。

其他回答

表达式<Func<T1, T2, T3,…>> and Func<T1, T2, T3,…>,没有给出第二个情况下性能下降的提示。

下面是代码示例,演示了我的意思:

[TestMethod]
public void QueryComplexityTest()
{
    var users = _dataContext.Users;

    Func<User, bool>                funcSelector =       q => q.UserName.StartsWith("Test");
    Expression<Func<User, bool>>    expressionSelector = q => q.UserName.StartsWith("Test");

    // Returns IEnumerable, and do filtering of data on client-side
    IQueryable<User> func = users.Where(funcSelector).AsQueryable();
    // Returns IQuerible and do filtering of data on server side
    // SELECT ... FROM [dbo].[User] AS [t0] WHERE [t0].[user_name] LIKE @p0
    IQueryable<User> exp = users.Where(expressionSelector);
}

如前所述,延迟加载和延迟执行

LINQ to object和LINQ to XML (IEnumerable)与LINQ to SQL(IQueryable)有何不同

如何建立一个数据访问层,业务层,和表示层与LINQ在所有层....这是个很好的例子。

正如大多数人所说,我认为最被误解的部分是假设LINQ只是T-SQL的替代品。我的经理认为自己是一个TSQL专家,他不让我们在项目中使用LINQ,甚至讨厌微软发布这样的东西!!

The fact that you can't chain IQueryable because they are method calls (while still nothing else but SQL translateable!) and that it is almost impossible to work around it is mindboggling and creates a huge violation of DRY. I need my IQueryable's for ad-hoc in which I don't have compiled queries (I only have compiled queries for the heavy scenarios), but in compiled queries I can't use them and instead need to write regular query syntax again. Now I'm doing the same subqueries in 2 places, need to remember to update both if something changes, and so forth. A nightmare.

我认为关于LINQ to SQL的第一个误解是,你仍然必须了解SQL才能有效地使用它。

关于Linq to Sql的另一个误解是,为了让它工作,你仍然必须降低数据库的安全性到荒谬的地步。

第三点是将Linq to Sql与动态类一起使用(意味着类定义是在运行时创建的)会导致大量的即时编译。这绝对会破坏性能。