[英]Is binding an ItemsControl to an ObservableCollection<T> more efficient than a 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
更有效?
另外,可以將上述功能之一編碼為更有效嗎?
編輯
我正在使用該函數返回一些對象,這些對象隨后將在ListView中顯示。 然后,我遍歷這些相同的對象以檢查是否出現字符串。
謝謝。
這在很大程度上取決於您要做什么。 例如,如果您使用FirstOrDefault(p => ....)
,yield方法可以更快,因為不需要將所有內容存儲到列表中;如果第一個元素是正確的元素,則list方法會有一些開銷(當然yield方法也有開銷,但正如我所說,這取決於。
如果要一遍又一遍地遍歷數據,則應使用該列表。
這取決於很多事情。
這是在List<T>
上使用IEnumerable<T>
一些原因:
FirstOrDefault
, Any
, Take
等)。 ToList()
(例如Fibonacci系列)。 當您不應該在List<T>
使用IEnumerable<T>
List<T>
:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.