Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# IEnumerable理解vs返回集合类型_C#_List Comprehension - Fatal编程技术网

C# IEnumerable理解vs返回集合类型

C# IEnumerable理解vs返回集合类型,c#,list-comprehension,C#,List Comprehension,在任何情况下,当出现以下情况时: public IEnumerable<Foo> Foobar (Bar bar) { List<Foo> result = new List<Foo>() foreach(var Qux in bar.QuxSource) { Foo item; ... //a procudure that is intricate enough not to be clearly re

在任何情况下,当出现以下情况时:

public IEnumerable<Foo> Foobar (Bar bar)
{
    List<Foo> result = new List<Foo>()
    foreach(var Qux in bar.QuxSource)
    {
        Foo item;
        ... //a procudure that is intricate enough not to be clearly repressentable with a LINQ method
        result.Add(item);
        ... //The aforementioned inticate proceduce continues. Possiblily adding more items to result
    }
    return result;
}
public IEnumerable Foobar(Bar)
{
列表结果=新列表()
foreach(bar.QuxSource中的变量Qux)
{
Foo项目;
…//一个非常复杂的过程,不能用LINQ方法清楚地表示出来
结果.添加(项目);
…//上述初始化过程继续。可能会向结果中添加更多项
}
返回结果;
}
优先于:

public IEnumerable<Foo> Foobar (Bar bar)
{
    foreach(var Qux in bar.QuxSource)
    {
        Foo item;
        ... //a procudure that is intricate enough not to be clearly repressentable with a LINQ method
        yield return item;
        ... //The aforementioned inticate proceduce continues. Possiblily yielding more items
    }
}
public IEnumerable Foobar(Bar)
{
foreach(bar.QuxSource中的变量Qux)
{
Foo项目;
…//一个非常复杂的过程,不能用LINQ方法清楚地表示出来
收益回报项目;
…//上述初始化过程继续。可能会产生更多项
}
}
我的意思是后者显然很棒。 由于延迟操作的好处,如果我只使用Foobar(someBar).First(),它就不必生成所有返回的项

我看到有经验的程序员经常使用前者。(我猜他们不是现代C#中最新的列表压缩)。 那么,在某些情况下,前父亲是否更好? (仅查看库代码,以重用为目标) 我在想,如果能够制作这些物品,可能需要一些外部资源,比如打开一个文件。 foreach的用例是什么?
我想您的示例用例是正确的,但更一般地说,如果:

  • 源使用稀缺资源,并且需要保证枚举数将被处理(如果您开始枚举后一种方法并且停止中间,而不处理枚举数,它将被打开)
  • 应尽快列举来源
  • 您必须保证对整个源进行评估

当对源序列的访问受到时间限制或应限制在狭窄的时间窗口内时,首选第一种方法(急切地枚举源序列),即使用Linq to SQL或Linq to Entities提供程序从数据库检索数据时。在第二种方法中,您依赖于使用者来枚举您的源代码,这可能需要更长的时间——一般来说,您不想让数据库连接保持那么长的打开时间