C# 将嵌套循环重构为单个LINQ查询
我正在尝试将其重构为一个查询:C# 将嵌套循环重构为单个LINQ查询,c#,.net,linq,C#,.net,Linq,我正在尝试将其重构为一个查询: while (IsRunning) { ... //specialPoint is a string foreach (PointTypeItem pointTypeItem in PointTypeItemCollection) { foreach (PointItem pointItem in pointTypeItem.PointItemCollection) { //Replac
while (IsRunning)
{
...
//specialPoint is a string
foreach (PointTypeItem pointTypeItem in PointTypeItemCollection)
{
foreach (PointItem pointItem in pointTypeItem.PointItemCollection)
{
//Replace the point name with point ID
if (specialPoint.Contains(pointItem.PointName))
{
replacedCode += s.Replace(specialPoint , pointItem.ID);
//I want to go back to the beginning point of while (IsRunning) from here
//Simply putting continue; here won't work
}
}
}
}
我基本上想把它变成一个LINQ查询,但我一直在写一个。事实上,我甚至不确定我的方向是否正确
var results = from pointTypeItem in ddcItem.PointTypeItemCollection
where pointTypeItem.PointItemCollection.Any(pointItem => pointName.Contains(pointItem.PointName))
select //What do I select?
获取一个IEnumerable
获取一个
IEnumerable
您可以使用SelectMany()扩展方法执行此操作:
PointTypeItemCollection.SelectMany(pointCollection => pointCollection.PointItemCollection)
.Where(pointItem => pointItem.PointName.Contains(specialPoint))
.Select(pointItem => pointItem.ID);
可以使用SelectMany()扩展方法执行此操作:
PointTypeItemCollection.SelectMany(pointCollection => pointCollection.PointItemCollection)
.Where(pointItem => pointItem.PointName.Contains(specialPoint))
.Select(pointItem => pointItem.ID);
没有任何值就很难进行测试,但是像这样的东西呢
replacedCode = string.Concat(
this.PointTypeItemCollection.SelectMany(i => i.PointItemCollection)
.Where(i => specialPoint.Contains(i.PointName))
.Select(i => s.Replace(specialPoint, i.ID))
);
没有任何值就很难进行测试,但是像这样的东西呢
replacedCode = string.Concat(
this.PointTypeItemCollection.SelectMany(i => i.PointItemCollection)
.Where(i => specialPoint.Contains(i.PointName))
.Select(i => s.Replace(specialPoint, i.ID))
);
生病了,我从来都不知道你能把这个条款藏在里面!谢谢非常insightful@l46kok这实际上不是一个嵌套查询。它将被转换为对
SelectMany
的单个调用,而不是对每个查询执行查询。@Richard根据OP中代码中的注释,他需要在查询结束时进行第一次调用。@Servy可能,如果的内容没有意义:不清楚s
是什么。注释会建议在specialPoint
(specialPoint.Replace(pointItem,pointItem.ID)
)中进行替换,但是如果不需要(如果名称不存在,则替换将是不可操作的)。生病了,我从来不知道可以将from子句嵌套在里面!谢谢非常insightful@l46kok这实际上不是一个嵌套查询。它将被转换为对SelectMany
的单个调用,而不是对每个查询执行查询。@Richard根据OP中代码中的注释,他需要在查询结束时进行第一次调用。@Servy可能,如果的内容没有意义:不清楚s
是什么。注释建议在specialPoint
(specialPoint.Replace(pointItem,pointItem.ID)
)中进行替换,但是如果不需要(如果名称不存在,则替换将是不可操作的)。无论如何,您仍然会遍历每个项目,那么这次重构的目的是什么?什么是s
,什么是replacedCode
?你能提供一个简单的例子和期望的结果吗?不管怎样,你仍然会迭代每个项目,那么这次重构的目的是什么?什么是s
,什么是replacedCode
?你能提供一个简单的例子和期望的结果吗?