簡體   English   中英

是IEnumerable <T> 功能比列表更有效 <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更有效?

另外,可以將上述功能之一編碼為更有效嗎?

編輯

我正在使用該函數返回一些對象,這些對象隨后將在ListView中顯示。 然后,我遍歷這些相同的對象以檢查是否出現字符串。

謝謝。

這在很大程度上取決於您要做什么。 例如,如果您使用FirstOrDefault(p => ....) ,yield方法可以更快,因為不需要將所有內容存儲到列表中;如果第一個元素是正確的元素,則list方法會有一些開銷(當然yield方法也有開銷,但正如我所說,這取決於。

如果要一遍又一遍地遍歷數據,則應使用該列表。

這取決於很多事情。

這是在List<T>上使用IEnumerable<T>一些原因:

  1. 當您迭代集合的一部分時(例如,使用FirstOrDefaultAnyTake等)。
  2. 當您有大量收藏時,可以使用ToList() (例如Fibonacci系列)。

當您不應該在List<T>使用IEnumerable<T> List<T>

  1. 當您多次在不同條件列舉一個數據庫查詢(您可以在內存中的結果)。
  2. 當您要遍歷整個集合一次以上時-無需每次都創建迭代器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM