c# – LINQ – 选择多个OrderBy外值然后选择Inner Value

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

两者都返回相同的结果.一个比另一个快吗?你觉得哪一个看起来更好?思考?

解决方法:

是,有一点不同.您的查询返回错误的结果.检查以下输入数组的查询结果:

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

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

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

>输入数组中的元素.第一个是“安妮威廉姆斯”.如果没有更多元素,则结束查询
>它被分成几部分,所以我们得到:[“安妮”,“威廉姆斯”].
> Sort应用于当前输入元素“Anne Williams”和分割部分[“Anne”,“Williams”].
>分类元素一个接一个地返回:“Anne来自Anne Williams”和“来自Anne Williams的Williamscame”.
>它回到第1点.

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

>输入数组中的元素.第一个是“安妮威廉姆斯”.如果没有更多元素转到5.
>它被分成几部分,所以我们得到:[“安妮”,“威廉姆斯”].
>元素一个接一个地返回:“Anne来自Anne Williams”和“来自Anne Williams的Williamscame”.
>它回到第1点.
>排序适用于所有选定的元素.

上一篇:c# – 如何为LINQPad设置NetFx40_LegacySecurityPolicy?


下一篇:c# – 带有long where子句的Linq