如何减少多个嵌套的foreach块 [英] How to reduce multiple nested foreach blocks

查看:163
本文介绍了如何减少多个嵌套的foreach块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况:

  var Ids = object1.GetIds(); //返回IEnumerable< int> 
foreach(Ids中的var id)
{
foreach(object1.GetRelatedObjects(id)中的var relatedObject)
{
//做某事与相关的对象






$ b在这种情况下,我想摆脱第一个foreach并将这个逻辑简化为单一的foreach。如何才能实现这一点?



应该可以用LINQ表达一些类似的方法吗?

解决方案

当两个循环之间没有任何内容时,在嵌套之前或之后,可以使用 SelectMany 将两个循环扁平化 / p>

  foreach(Ids.SelectMany(object1.GetRelatedObjects)中的var relatedObject){
...
}

这个循环与循环之间的一个主要区别是 id 不在范围之内。假设 relatedObject 暴露了一个public Id 属性,这在你的情况下不应该是一个问题,因为你可以提取 id 返回

  var id = relatedObject.Id; 


I have the following scenario:

var Ids = object1.GetIds(); // returns IEnumerable<int>
foreach (var id in Ids)
{
    foreach (var relatedObject in object1.GetRelatedObjects(id))
    {
    // Do Something with related object
    }
}

In this case, i want to get rid of from the first foreach and reduce this logic into single foreach. How could i achieve this?

Should it be possible with LINQ expression some similar methodology?

解决方案

When there is nothing between the two loops, before or after the nested one, you can use SelectMany to "flatten" two loops into one:

foreach (var relatedObject in Ids.SelectMany(object1.GetRelatedObjects)) {
    ...
}

One major difference between this loop and the loop that you have is that id is no longer in scope. Assuming that relatedObject exposes a public Id property, this should not be a problem in your situation, because you could extract the id back with

var id = relatedObject.Id;

这篇关于如何减少多个嵌套的foreach块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆