3

如果我想返回输入集合,在迭代器块中使用 return 语句而不是 foreach 的最聪明的方法是什么?

public IEnumerable<T> Filter(IEnumerable<T> collection)
{
   if (someCondition)
   {
       // return collection; - cannot be used because of "yield" bellow
       foreach (T obj in collection)
       {
          yield return obj;
       } 
       yield break;
   }
   yield return new T();
}
4

2 回答 2

3

恐怕这就是您在迭代器块中所能做的一切。yield!在 F# 中没有等价物,也没有yield foreach. 这很不幸,但事实就是这样:(

当然,您可以首先避免使用迭代器块:

public IEnumerable<Class> Filter(IEnumerable<Class> collection)
{
   return someCondition ? collection : Enumerable.Repeat(new Class(2), 1);
}

或者,如果您有更复杂的逻辑:

public IEnumerable<Class> Filter(IEnumerable<Class> collection)
{
   return someCondition ? collection : FilterImpl(collection);
}

private IEnumerable<Class> FilterImpl(IEnumerable<Class> collection)
{
    yield return new Class(2);
    yield return new Class(1);
    // etc
}
于 2011-07-11T05:24:04.580 回答
0

In this case, I would probably do:

public IEnumerable<T> Filter(IEnumerable<T> collection)
{
   if (someCondition)
   {
       return collection
   }
   return new [] {new T()};
}

In more complex cases, where some collections are optionally included in the return value, I use Union.

于 2011-07-13T06:42:23.123 回答