集
飽含不重復元素的集合稱為”集(set)”. .NET4包含兩個集(HashSet<T>和SortedSet<T>),他們都實現ISet<T>接口.HashSet<T>即包含不重復元素的無序列表,SortedSet<T>集包含不重復元素的有序列表.
ISet<T>接口提供的方法可以創建合集,交集,或者給出一個集合時另一個集的超集或子集的信息.
案例:
//使用HashSet:重復的元素自動被移除,但是不排序
var set = new HashSet<int>() { 5, 9, 2, 1, 2, 2, 3, 7, 4, 9, 9 };
foreach (var item in set)
{
Console.WriteLine(item);
}
Console.ReadKey();
同樣的代碼,將HashSet換成SortedSet:
//使用SortedSet:重復的元素自動被移除,還進行了排序
var set = new SortedSet<int>() { 5, 9, 2, 1, 2, 2, 3, 7, 4, 9, 9 };
foreach (var item in set)
{
Console.WriteLine(item);
}
Console.ReadKey();
總結:
1.HashSet和SortedSet主要的作用是用來進行兩個集合求交集,並集,差集等運算. 集合中包含一組不重復出現且無特性順序的元素.前者不會自動排序,后者會加入元素后,自動排序
2.兩者都無法從特定位置訪問其中某個元素.
3.可以使用其查找功能:
Set.Contains(“value”) //返回true或false
4.對集合的操作:
a . SymmetricExceptWith:僅包含該對象或指定集合中存在的元素(但不可同時包含兩者中的元素).去除交集,剩下兩個集合元素.
b . UnionWith:包含該對象本身和制定集合中存在的所有元素. 並集
c . ExceptWith從當前HashSet<T>對象中移除指定集合中的所有元素 . 差集
d . IntersectWith:僅包含該對象和指定集合中存在的元素. 交集
5.SortedSet對象,可以調用GetViewBetween,Max,Min方法
6.除了SortedSet外,System.Collections.Generic命名空間下,還提供了SortedDictionary和SortedList兩個類.
測試HashSet內置的一些方法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 集
{
class Program
{
static void Main(string[] args)
{
HashSet<char> setA = new HashSet<char>();
HashSet<char> setB = new HashSet<char>();
setA.Add('A');
setA.Add('B');
setA.Add('C');
setB.Add('C');
setB.Add('D');
setB.Add('E');
Show("Initial content of setA: ", setA);
Show("Initial content of setB: ", setB);
setA.SymmetricExceptWith(setB); //把 setA、setB 各自特有、對方沒有的元素列出來
Show("setA after Symmetric difference with SetB: ", setA);
setA.UnionWith(setB); //把 setA、setB 的全部元素列出來 (union 並集)
Show("setA after union with setB: ", setA);
setA.ExceptWith(setB); //把 setA 中,所擁有的 setB 元素移除
Show("setA after subtracting setB: ", setA);
Console.WriteLine();
Console.Read();
}
static void Show(string msg, HashSet<char> set)
{
Console.Write(msg);
foreach (char ch in set)
Console.Write(ch + " ");
Console.WriteLine();
}
}
}
測試SortedSet的方法:
using System;
using System.Collections.Generic;
using System.Linq;//此為Max(),Min()方法的必要調用
using System.Text;
using System.Threading.Tasks;
namespace 集
{
class Program
{
static void Main(string[] args)
{
var set = new SortedSet<int>() { 5, 9, 2, 1, 2, 2, 3, 7, 4, 9, 9 };
foreach (int element in set)
Console.WriteLine(string.Format(" {0}", element));
Console.WriteLine("Max: " + set.Max() );
Console.WriteLine("Min: " + set.Min() );
Console.Write("<br>取 2 ~ 5 之間的值: ");
//只取值為 2 ~ 5 之間的元素
var subSet = set.GetViewBetween(2, 5);
foreach (int i in subSet)
{
Console.Write(i + " ");
}
Console.WriteLine();
Console.Read();
}
static void Show(string msg, HashSet<char> set)
{
Console.Write(msg);
foreach (char ch in set)
Console.Write(ch + " ");
Console.WriteLine();
}
}
}