HashSet和IEnumerables的执行

时间:2014-11-05 10:31:25

标签: c#

当HashSet需要时,HashSet是否始终执行未执行的可发生的数量?

例如:

list = new List { 1 ..... 1000);

var linq = list.Where(x => x > 10);

var hashSet = new HashSet(linq);

现在当我在hashSet.Contains(7)中拨打for loop时,hashSet是否会在需要时始终执行Where语句?

for(int i = 0; i < 10000; ..)
{
  hashSet.Contains(7);
}

2 个答案:

答案 0 :(得分:5)

不,只有在HashSet构建IEnumerable<T>时才会执行查询(构造函数枚举它以填充集合),因此不会执行后。

答案 1 :(得分:3)

正如您在HashSet<T>构造函数

中看到的那样
// this is the constructor you are using
public HashSet(IEnumerable<T> collection)
        : this(collection, EqualityComparer<T>.Default) { }

public HashSet(IEnumerable<T> collection, IEqualityComparer<T> comparer)
        : this(comparer) {
        ...
        // removed unnecessary parts...
         this.UnionWith(collection);
       ...
    }

它使用给定的UnionWith调用IEnumerable<T>方法,迭代项目并添加它们(如果它们尚不存在)

public void UnionWith(IEnumerable<T> other)
{
    ...
    foreach (T item in other) 
    {
         AddIfNotPresent(item);
    }
}

因此查询只执行一次。