4

我一直在浏览Linqpad示例 linq 示例。在“Projecting - SelectMany”下,他们要求您尝试将以下 linq 语法翻译成 Fluent 语法。这是那里的样本:

var fullNames = new[] { "Anne Williams", "John Fred Smith", "Sue Green" }
    .AsQueryable();

IEnumerable<string> query =
    from fullName in fullNames
    from name in fullName.Split()
    orderby fullName, name
    select name + " came from " + fullName;

query.Dump();

我使用以下方法对其进行了转换:

var myQuery = fullNames
   .SelectMany(
      fullName => fullName.Split()
          .OrderBy(fn => fullName)
          .ThenBy(fn=> fn)
      , (fullName, name) => ((name + " came from ") + fullName)
   );

但是 linqpad 生成以下内容:

 IEnumerable<string> query2 = fullNames
    .SelectMany (fName => fName.Split().Select (name => new { name, fName } ))
    .OrderBy (x => x.fName)
    .ThenBy  (x => x.name)
    .Select  (x => x.name + " came from " + x.fName);

两者都返回相同的结果。一个比另一个快吗?你觉得哪一个更好看?想法?

4

1 回答 1

4

是,有一点不同。您的查询返回不正确的结果。检查以下输入数组的查询结果:

var fullNames = new[] { "Anne Williams", "Sue Green", "John Fred Smith" }
                .AsQueryable();

示例查询结果:

Anne came from Anne Williams
Williams came from Anne Williams
Fred came from John Fred Smith
John came from John Fred Smith
Smith came from John Fred Smith
Green came from Sue Green
Sue came from Sue Green

您的查询结果:

Anne came from Anne Williams
Williams came from Anne Williams
Green came from Sue Green
Sue came from Sue Green
Fred came from John Fred Smith
John came from John Fred Smith
Smith came from John Fred Smith

问题是您要分别为源数组中的每个项目排序,因此您的项目与输入数组中的顺序完全相同。示例查询在生成所有项目后对其进行排序。


您的查询以下列方式工作:

  1. 取输入数组中的元素。第一个是"Anne Williams". 如果没有更多元素,则结束查询。

  2. 它被分成几部分,所以我们得到:["Anne", "Williams"].

  3. 排序应用于当前输入元素"Anne Williams"和拆分部分["Anne", "Williams"]

  4. 排序后的元素一个接一个地返回:"Anne came from Anne Williams""Williamscame from Anne Williams".

  5. 它回到第 1 点。

示例查询以这种方式工作:

  1. 取输入数组中的元素。第一个是"Anne Williams". 如果没有更多元素转到 5。

  2. 它被分成几部分,所以我们得到:["Anne", "Williams"].

  3. 元素一个接一个地返回:"Anne came from Anne Williams""Williamscame from Anne Williams".

  4. 它回到第 1 点。

  5. 排序应用于所有选定的元素。

于 2013-04-12T19:34:58.663 回答