在针对对象集合的LINQ查询背后,究竟发生了什么?它只是语法糖吗,还是有其他的事情发生,使得它成为更高效的查询?
您是指查询表达式,还是查询背后的操作?
查询表达式首先会被扩展为“正常”的C#代码。例如:
var query = from x in source
where x.Name == "Fred"
select x.Age;
被翻译成:
var query = source.Where(x => x.Name == "Fred")
.Select(x => x.Age);
var query = Enumerable.Select(Enumerable.Where(source, x => x.Name == "Fred"),
x => x.Age);
接下来,Select
和Where
的实现变得很重要。不考虑错误检查,它们大致是这样的:
public static IEnumerable<T> Where<T>(this IEnumerable<T> source,
Func<T, bool> predicate)
{
foreach (T element in source)
{
if (predicate(element))
{
yield return element;
}
}
}
public static IEnumerable<TResult> Select<TSource, TResult>
(this IEnumerable<TSource> source,
Func<TSource, TResult> selector)
{
foreach (TSource element in source)
{
yield return selector(element);
}
}
这只是一种语法糖,其中没有涉及到任何魔法。
你可以用"C#"或其他语言手写等效的代码,它们将会执行相同的功能。
(当然,编译器会生成高效的代码,所以它生成的代码可能比你自己写的代码更加高效,因为你可能不知道如何编写最有效的代码。)