gpt4 book ai didi

c# - LINQ 会根据输入类型使用专门/优化版本的函数吗?

转载 作者:太空狗 更新时间:2023-10-30 00:34:53 32 4
gpt4 key购买 nike

如果我使用 LINQ 执行以下操作:

void DoSomeStuffWithHashSet()
{
HashSet<int> set = new HashSet<int>();
for (int i = 0; i < 100; ++i) set.Add(i);
if (Lookup(set, new Random().NextInt(200))
System.Console.WriteLine("Yey");
else
System.Console.WriteLine("Ney");
}

bool Lookup(IEnumerable<int> haystack, int needle)
{
// O(N) search or HashSet<int>.Contains()?
return Enumerable.Contains(collection, needle);
}

Enumerable.Contains() 会解析为 HashSet 上的优化实现,还是会执行一个简单的搜索而不考虑输入?

最佳答案

是的,它将使用 HashSet<T>.Contains . HashSet<T>工具 ICollection<T>并根据 documentation for Enumerable.Contains :

If the type of source implements ICollection<T>, the Contains method in that implementation is invoked to obtain the result. Otherwise, this method determines whether source contains the specified element.

总是,总是,总是检查文档!

关于c# - LINQ 会根据输入类型使用专门/优化版本的函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6312232/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com