具有收益率的 IEnumerable<T> 函数是否比 List<T> 函数更有效?

Is the IEnumerable<T> function with a yield more efficient than the List<T> function?

我正在编写一个 C# 表单应用程序,想知道以下两个函数是否能达到相同的结果:

public List<object> Method1(int parentId)
{
    List<object> allChildren = new List<object>();
    foreach (var item in list.Where(c => c.parentHtmlNodeForeignKey == parentId))
    {
        allChildren.Add(item);
        allChildren.AddRange(Method1(item.id));
    }
    return allChildren;
}
public IEnumerable<object> Method2(int parentId)
{
    foreach (var item in list.Where(c => c.parentHtmlNodeForeignKey == parentId))
    {
        yield return item;
        foreach (var itemy in Method2(item.id))
        {
            yield return itemy;
        }
    }
}

我说 Method1 函数比 Method2 函数更有效,我说得对吗?

此外,是否可以对上述任一函数进行编码以提高效率?

编辑

我正在使用该函数 return 一些对象,然后显示在 ListView 中。然后我循环遍历这些相同的对象以检查是否出现字符串。

谢谢。

这在很大程度上取决于您想做什么。例如,如果您使用 FirstOrDefault(p => ....) yield 方法可以更快,因为它不需要将所有内容存储到列表中,并且如果第一个元素是正确的,则 list 方法会有一些开销(当然 yield 方法有也有开销,但正如我所说,这取决于 )。

如果您想一遍又一遍地遍历数据,那么您应该使用列表。

这取决于很多事情。

以下是使用 IEnumerable<T> 而不是 List<T> 的一些原因:

  1. 当您迭代集合的 部分 时(例如,使用 FirstOrDefaultAnyTake 等)。
  2. 当你有一个 集合并且你可以 ToList() 它(例如斐波那契数列)。

什么时候你不应该使用 IEnumerable<T> 而不是 List<T>:

  1. 当您在不同条件下枚举数据库查询 多次 次(您可能需要内存中的结果)。
  2. 当您想多次迭代整个集合时 - 无需每次都创建迭代器。