Does Linq Contains() check for HashSet?

拥有回忆 提交于 2019-12-23 07:06:08

问题


Sometimes a HashSet is exposed through a property as an IEnumerable.

It is well known that for enumerable.Count() the code checks if it is a collection, so it doesn't enumerate the whole list, but takes a shortcut.

Is there any similar check for using the Linq version of enumerable.Contains(x) and HashSets?


回答1:


From the reference source, yes it does, though not directly:

public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value) {
    ICollection<TSource> collection = source as ICollection<TSource>;
    if (collection != null) return collection.Contains(value);
    return Contains<TSource>(source, value, null);
}

If the source enumerable implements ICollection<T> (and HashSet<T> does), then it uses the collection's Contains method.




回答2:


Note also it is documented to look for ICollection<T> (see Remarks).



来源:https://stackoverflow.com/questions/25275071/does-linq-contains-check-for-hashset

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!