我一直在浏览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);
两者都返回相同的结果。一个比另一个快吗?您认为哪一个看起来更好?想法?
答案 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
问题是您是否单独为源数组中的每个项目进行排序,因此您的项目与输入数组的顺序完全相同。样本查询在生成后对所有项目进行排序。
您的查询以下列方式运作:
输入来自输入数组的元素。第一个是"Anne Williams"
。如果没有更多元素,则结束查询。
它分为几个部分,因此我们得到:["Anne", "Williams"]
。
排序适用于当前输入元素"Anne Williams"
和拆分["Anne", "Williams"]
。
分类元素将陆续返回:"Anne came from Anne Williams"
和"Williamscame from Anne Williams"
。
它回到第1点。
示例查询以这种方式工作:
输入来自输入数组的元素。第一个是"Anne Williams"
。如果没有更多元素转到5。
它分为几个部分,因此我们得到:["Anne", "Williams"]
。
元素一个接一个地返回:"Anne came from Anne Williams"
和"Williamscame from Anne Williams"
。
它回到第1点。
排序适用于所有选定的元素。