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

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

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


当前回答

我知道延迟执行的概念现在应该被灌输给我了,但这个例子确实帮助我实际掌握了它:

static void Linq_Deferred_Execution_Demo()
{
    List<String> items = new List<string> { "Bob", "Alice", "Trent" };

    var results = from s in items select s;

    Console.WriteLine("Before add:");
    foreach (var result in results)
    {
        Console.WriteLine(result);
    }

    items.Add("Mallory");

    //
    //  Enumerating the results again will return the new item, even
    //  though we did not re-assign the Linq expression to it!
    //

    Console.WriteLine("\nAfter add:");
    foreach (var result in results)
    {
        Console.WriteLine(result);
    }
}

上面的代码返回如下:

Before add:
Bob
Alice
Trent

After add:
Bob
Alice
Trent
Mallory

其他回答

我不知道这是否属于误解,但对我来说,就是未知。

我很高兴了解了DataLoadOptions以及在进行特定查询时如何控制连接哪些表。

更多信息请参见这里:MSDN: DataLoadOptions

正如大多数人所说,我认为最被误解的部分是假设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.

我发现很难找到关于匿名类型的明确信息,特别是在web应用程序的性能方面。 此外,我会建议更好和实用的lambda表达式示例和“如何”部分在查询和性能相关的主题。

希望我的简短清单能有所帮助!

我不认为每个人都能理解嵌套循环有多容易。

例如:

from outerloopitem in outerloopitems
from innerloopitem in outerloopitem.childitems
select outerloopitem, innerloopitem