c# - 如何从 IEnumerable 方法调用 IEnumerable 方法?

标签 c# .net ienumerable

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

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

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

   GetOtherObjects();
}

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

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

最佳答案

添加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());  
}

关于c# - 如何从 IEnumerable 方法调用 IEnumerable 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57975804/

相关文章:

c# - 将 VB 转换为 C# - My.Application.Info.DirectoryPath

c# - 如何检查 Json 对象是否已填充所有值

c# - MVC4 操作中的反序列化对象导致空值

c# - 锁屏下的WP8定时器应用

c# - 在 Linux 上使用 Mono 上的 system.windows.forms 进行开发

.net - 何时使用 IComparable<T> 与何时使用IComparer<T>

c# - GetHashCode 相等

c# - 如何跳过 Json.Net 中 IEnumerable 类型的默认 JavaScript 数组序列化?

c# - 查找多种类型的所有控件?

javascript - 访问 javascript 端 POST 请求返回的 IEnumerable (Web API)