HashSet, HashTable

HashTable 存储键值对 , Hashtable和Dictionary<TKey,TValue>都是存键值对

HashSet 只存储值盛放不同的数据,相同的数据只保留一份

HashSet<T>对集合运算的操作

public void IntersectWithTest() {

  HashSet<int> set1 = new HashSet<int>() { 1, 2, 3 };

  HashSet<int> set2 = new HashSet<int>() { 2, 3, 4 };

  set1.IntersectWith(set2);  //取交集,结果赋值给set1

  foreach (var item in set1) {

    Console.WriteLine(item);

  } //输出:2,3

}

同样,还有 并集UnionWith, 排除集 ExceptWith

.net 3.5为泛型集合提供了一系列的扩展方法,使得所有的泛型集合具备了set集合操作的能力

扩展方法

public void IntersectTest() {

  HashSet<int> set1 = new HashSet<int>() { 1, 2, 3 };

  HashSet<int> set2 = new HashSet<int>() { 2, 3, 4 };

  IEnumerable<int> set3=set1.Intersect(set2);

  foreach (var item in set1) { Console.WriteLine(item); }

  foreach (var item in set3) { Console.WriteLine(item); }

  //输出:o //set1 : 1,2,3 //set3 : 2,3

}

IEnumerable<T> 其他的扩展方法也是一样,都是不改变调用方法的数组,而是产生并返回新的IEnumerable<T>接口类型的数组

HashSet<T>是一个Set集合,查询上有较大优势,但无法通过下标方式来访问单个元素

原文地址:https://www.cnblogs.com/rockywood/p/6551395.html