3 ms·
LINQ is pretty basic if you are just using the IEnumerable overloads. It get's more interesting when you use the IQueryable versions of things. LINQ to SQL and
by MarkSweep 8y ago
LINQ is pretty basic if you are just using the IEnumerable overloads. It get's more interesting when you use the IQueryable versions of things. LINQ to SQL and Entry Framework provide IQueryable implementations that turn C# code in to SQL. This code snippet demonstrates the C# feature these frameworks relies on:
using System;
using System.Linq.Expressions;
class Program
{
static void Main(string[] args)
{
Expression<Func<int, int, int>> expr = (a, b) => a + b;
Console.WriteLine(expr);
Func<int, int, int> fun = expr.Compile();
Console.WriteLine(fun(1, 2));
}
}
When run, this outputs:
(a, b) => (a + b)
3
When a Expression<T> variable is assigned to or a method taking an Expression<T> parameter, the C# code is not translated into MSIL (normal C# is compiled to MSIL). Rather it is translated into an AST. In my example I just compiled it to MSIL, however LINQ-to-SQL and Entity Framework translate the AST to SQL. This macro-like capability is the true power of LINQ. The rest is syntactic sugar (though very delicious sugar).
If I were to try to critique LINQ, it would the normal ORM complaints. Sometimes you have to care about what is going on underneath in the C#-to-SQL translation. Your code may compile, but at runtime the generated SQL might have terrible performance.