恩冗长的LINQ EX pressions?冗长、LINQ、pressions、EX

2023-09-05 04:06:09 作者:一念執著

我突然想到,我写出来的LINQ语句简单,但别人可以定义为冗长的方式;

一个简单的例子:

 返回_entries
    。凡(X => x.Context.Equals(上下文))
    。凡(X => x.Type == typeof运算(T))
    。选择(X => x.Value)
    .Cast< T>()
    。单();
 

可以简化为:

 返回_entries
    。凡(X => x.Context.Equals(上下文)及&安培; x.Type == typeof运算(T))
    。选择(X =>(T)x.Value)
    。单();
 
每日积累 背三句 guess expressions

[问题] 从长远来看,这是更好的编码做法?即长(简单的)LINQ链或短LINQ链更复杂的选择/等?

这是正确的,假定这些LINQ的语句将被编译器进行优化?

解决方案   

从长远来看,这是更好的编码做法?

我preFER简短。这是更具可读性。 LINQ的全部意义在于使code读起来更像业务领域的逻辑。

  

这是正确的,假定这些LINQ的语句将被编译器进行优化?

没有;优化是通过完成的运行时的,而不是由编译的。 LINQ到对象去哪儿,然后按照你描述的模式的选择条款在运行时优化到一个单一的,其中,选择目标,以避免造成过多的迭代器。 (虽然作为乔恩斯基特发现,有时可以产生在其中的表现实际上是下降的情况。像几乎所有的优化,这不是一个赢得100%的时间不幸的是我无法找到乔恩的那篇文章在这一刻。 )

It occurred to me that I write out linq statements in a simple, but what others may define as verbose manner;

A simple example:

return _entries
    .Where(x => x.Context.Equals(context))
    .Where(x => x.Type == typeof (T))
    .Select(x=>x.Value)
    .Cast<T>()
    .Single();

can be simplified to:

return _entries
    .Where(x => x.Context.Equals(context) && x.Type == typeof (T))
    .Select(x=>(T)x.Value)
    .Single();

[Question] In the long run, which is the better coding practice? i.e. long (and simple) linq chains or short linq chains with more complicated selectors/etc?

It is right to assume that these Linq statements will be optimized by the compiler?

解决方案

In the long run, which is the better coding practice?

I prefer short and simple. It's more readable. The whole point of LINQ is to make the code read more like the logic of the business domain.

It is right to assume that these Linq statements will be optimized by the compiler?

No; the optimization is done by the runtime, not by the compiler. LINQ-to-objects "Where" and "Select" clauses that follow the pattern you describe are optimized into a single "where-select" object at runtime to avoid creating too many iterators. (Though as Jon Skeet discovered, that can sometimes produce situations in which performance is actually degraded; like almost all "optimizations", it's not a win 100% of the time. Unfortunately I can't find Jon's article on that at this moment.)

 
精彩推荐