C# 将冗长的LINQ语句翻译为;虚线;版本
以下是我编写的原始代码(用于测试目的):C# 将冗长的LINQ语句翻译为;虚线;版本,c#,linq,C#,Linq,以下是我编写的原始代码(用于测试目的): 提前多谢:-)我不能100%确定它在句法上是否完全相同,但在语义上是相同的: List<A037Line> a037Lines = propassBatchFolder.TextFiles. SelectMany(textFile => textFile.A037Lines). Where(a037Line => a037Line.NISS == "80061031738").
提前多谢:-)我不能100%确定它在句法上是否完全相同,但在语义上是相同的:
List<A037Line> a037Lines =
propassBatchFolder.TextFiles.
SelectMany(textFile => textFile.A037Lines).
Where(a037Line => a037Line.NISS == "80061031738").
ToList();
列表A037行=
propassBatchFolder.TextFiles。
选择多行(textFile=>textFile.a037行)。
其中(a037Line=>a037Line.NISS==“80061031738”)。
托利斯特();
如果从内部开始,将嵌套循环转换为查询会更容易
首先转换内部循环:
foreach (var textFile in propassBatchFolder.TextFiles) {
a037Lines.AddRange(
textFile.A037Lines.Where(a037Line => a037Line.NISS == "80061031738")
);
}
现在,您可以使用SelectMany
应用程序转换外循环:
var res = propassBatchFolder
.TextFiles
.SelectMany(textFile => textFile.A037Lines.Where(a037Line => a037Line.NISS == "80061031738"))
.ToList();
var res = propassBatchFolder
.TextFiles
.SelectMany(textFile => textFile.A037Lines)
.Where(a037Line => a037Line.NISS == "80061031738")
.ToList();
最后,您可以通过从内部移出Where
来减少嵌套SelectMany
:
var res = propassBatchFolder
.TextFiles
.SelectMany(textFile => textFile.A037Lines.Where(a037Line => a037Line.NISS == "80061031738"))
.ToList();
var res = propassBatchFolder
.TextFiles
.SelectMany(textFile => textFile.A037Lines)
.Where(a037Line => a037Line.NISS == "80061031738")
.ToList();
最终结果是一样的,但最终版本更具可读性。
中的是集合,其中进入。其中(x=>x.whatever.is.in.The.where)
和选择进入。选择(x=>x.whatever.you.select)
。试试看。我95%肯定resharper给了你从查询语法到方法语法的转换选项。根据每个规范的翻译有一些额外的代码来保持textFile
在范围内,但你是对的,这完全没有必要。
var res = propassBatchFolder
.TextFiles
.SelectMany(textFile => textFile.A037Lines)
.Where(a037Line => a037Line.NISS == "80061031738")
.ToList();