LINQ -选择多个顺序的外部值,然后内部值
本文关键字:外部 然后 内部 顺序 选择 LINQ | 更新日期: 2023-09-27 18:08:49
我一直在浏览Linqpad示例linq示例。在"投影-选择许多"下,他们要求您尝试将以下linq语法翻译为流利语法。这是一个示例:
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
问题是你对源数组中的每个项目分别排序,所以你的项目与输入数组中的顺序完全相同。示例查询在生成所有项后对它们排序。
查询的工作方式如下:
从输入数组中获取元素。第一个是
"Anne Williams"
。它被分成了几个部分,所以我们得到:
["Anne", "Williams"]
对电流输入元素
"Anne Williams"
和分割部分["Anne", "Williams"]
进行排序。排序后的元素依次返回:
"Anne came from Anne Williams"
和"Williamscame from Anne Williams"
返回到第1点
示例查询是这样工作的:
从输入数组中获取元素。第一个是
"Anne Williams"
。它被分成了几个部分,所以我们得到:
["Anne", "Williams"]
。元素依次返回:
"Anne came from Anne Williams"
和"Williamscame from Anne Williams"
。返回到第1点
排序应用于所有选定的元素