请帮我简化并转换为点符号linq查询

时间:2014-06-05 15:13:18

标签: c# performance linq

var query = (from objectType in _session.GetAll<ObjectType>()
  let currentVersion = objectType
      .ObjectTypeVersions.OrderByDescending(x =>x.ObjectTypeVersionId)
      .FirstOrDefault()
  where 
      objectType.Active && 
      currentVersion.Active && 
      objectType.ContentTemplate.Active
  select currentVersion);

我有这样的查询,我不明白它的作用。我想用方法语法重写它。

2 个答案:

答案 0 :(得分:3)

查询语法只是语法糖。您可以使用反编译器(如ILSpy)转换为扩展方法表示法。经过一些清理后,我得到的是:

var query = objectTypes.Select(objectType => new
{
    objectType = objectType, 
    currentVersion = objectType.ObjectTypeVersions
        .OrderByDescending(x => x.ObjectTypeVersionId).FirstOrDefault()
}).Where(x => x.objectType.Active && x.currentVersion.Active && 
    x.objectType.ContentTemplate.Active).Select(x => x.currentVersion);

作为参考,这是ILSpy生成的原始代码......基本上是相同的,但生成的变量名称不是有效的C#标识符,并且不必要地显式输入。

IEnumerable<ObjectTypeVersion> query = objectTypes.Select((ObjectType objectType) => new
{
    objectType = objectType,
    currentVersion = objectType.ObjectTypeVersions.OrderByDescending((ObjectTypeVersion x) => x.ObjectTypeVersionId).FirstOrDefault<ObjectTypeVersion>()
}).Where(<>h__TransparentIdentifier0 => <>h__TransparentIdentifier0.objectType.Active && <>h__TransparentIdentifier0.currentVersion.Active && <>h__TransparentIdentifier0.objectType.ContentTemplate.Active).Select(<>h__TransparentIdentifier0 => <>h__TransparentIdentifier0.currentVersion);

答案 1 :(得分:2)

我肯定会使用查询语法。但这里是lambda语法:

var query = _session.GetAll<ObjectType>()
     .Select(objectType => new {
          objectType,
          currentVersion = objectType.ObjectTypeVersions.OrderByDescending(otv => otv.ObjectTypeVersionId).FirstOrDefault()
      }).Where(x => x.objectType.Active && x.currentVersion.Active && x.objectType.ContentTemplate.Active)
        .Select(x => x.currentVersion);

这里的主要想法是创建匿名类型,其中包含objectType关键字引入的原始查询变量currenVersion和第二个let