因此,當我們有一個整數/字串/物件串列并嘗試使用 LINQ 搜索該串列中的元素時。
LINQ 是否在內部執行二進制搜索或線性搜索?
public class Person
{
public string Name { get; set; }
public string Address { get; set; }
}
我們的 LINQ 看起來像這樣:
List<Person> persons = new List<Person>();
persons.Where(x => x.Name == "kushal");
uj5u.com熱心網友回復:
Where不是對單個元素的搜索。這只是一種允許在每個元素上執行謂詞(回傳 true 或 false 的函式)并回傳謂詞為 true 的元素的方法。
為了在集合中移動,LINQ 使用迭代器,因此移動取決于迭代器。List<T>有一個專用的迭代器Where。您可以在 .NET 源代碼中看到這一點public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate):
...
if (source is List<TSource> list)
{
return new WhereListIterator<TSource>(list, predicate);
}
WhereListIterator的 MoveNext 依次使用 ListMoveNext和List<T>的MoveNext以下列方式一次移動一個專案:
_current = localList._items[_index];
_index ;
當您對此進行推理時,值得記住的是 LINQ 實際上并沒有在串列中移動。只有當您列舉結果時.Where- 例如使用foreachor ToList- 才完成真正的作業(遍歷元素并檢查謂詞是否為真)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/494194.html
