LINQ - 选择多个OrderBy外值然后选择Inner Value

时间:2013-04-12 19:23:08

标签: c# linq linqpad

我一直在浏览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);

两者都返回相同的结果。一个比另一个快吗?您认为哪一个看起来更好?想法?

1 个答案:

答案 0 :(得分: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点。

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

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

    2. 它分为几个部分,因此我们得到:["Anne", "Williams"]

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

    4. 它回到第1点。

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