【问题标题】:How to call an IEnumerable method from an IEnumerable method?如何从 IEnumerable 方法调用 IEnumerable 方法?
【发布时间】:2020-01-18 09:50:08
【问题描述】:

我有一个类似于以下的代码,但更复杂:

IEnumerable<SomeObject> GetObjects()
{
   if (m_SomeObjectCollection == null)
   {
      yield break;
   }

   foreach(SomeObject object in m_SomeObjectCollection)
   {
      yield return object;
   }

   GetOtherObjects();
}

IEnumerable<SomeObject> GetOtherObjects()
{
...
}

我刚刚意识到,GetOtherObjects() 方法不能从OtherObjects() 方法调用没有错误,但迭代停止。有什么办法解决吗?

【问题讨论】:

  • GetOtherObjects() 上执行foreach 就像您对m_SomeObjectCollection 所做的那样。
  • 如所写,您的方法首先不需要迭代器:return m_SomeObjectCollection ?? GetOtherObjects() ?? Enumerable.Empty&lt;SomeObject&gt;() 或其一些变体应该可以。 (不过,如果可以的话,首先尝试摆脱 null —— 始终实例化集合,即使是空的,作为不变量也是有用的。)

标签: c# .net ienumerable


【解决方案1】:

添加foreachyield return

IEnumerable<SomeObject> GetObjects()
{
   if (m_SomeObjectCollection == null)
   {
      yield break;
   }

   foreach(SomeObject item in m_SomeObjectCollection)
   {
      yield return item;
   }

   foreach (var item in GetOtherObjects())
     yield return item;
}

另一种可能是 Linq Concat:

Enumerable<SomeObject> GetObjects()
{
   return m_SomeObjectCollection == null
     ? new SomeObject[0] // yield break emulation: we return an empty collection
     : m_SomeObjectCollection.Concat(GetOtherObjects());  
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-17
    • 2023-03-31
    • 1970-01-01
    • 2012-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    相关资源
    最近更新 更多