将嵌套循环重构为单个LINQ查询

时间:2012-11-20 13:21:08

标签: c# .net linq

我正在尝试将其重构为一个查询:

 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?

3 个答案:

答案 0 :(得分:6)

var results = from pointTypeItem in ddcItem.PointTypeItemCollection
              from pointItem in pointTypeItem.PointItemCollection
              where specialPoint.Contains(pointItem.PointName)
              select pointItem.ID;

获得IEnumerable<the type of pointItem.ID>

答案 1 :(得分:2)

您可以使用SelectMany()扩展方法执行此操作:

 PointTypeItemCollection.SelectMany(pointCollection => pointCollection.PointItemCollection)
                .Where(pointItem => pointItem.PointName.Contains(specialPoint))
                .Select(pointItem => pointItem.ID);

答案 2 :(得分:0)

在没有任何价值的情况下进行测试非常困难,但是这样的事情呢?

      replacedCode = string.Concat(
        this.PointTypeItemCollection.SelectMany(i => i.PointItemCollection)
        .Where(i => specialPoint.Contains(i.PointName))
        .Select(i => s.Replace(specialPoint, i.ID))
      );