介紹
在C#中,集合是一種用于存儲和操作多個元素的數據結構。它們提供了各種操作,如添加、刪除、查找等,以及遍歷集合中的元素。集合通常根據其實現方式和行為特征進行分類。
集合繼承IEnumerable
在C#中,幾乎所有的集合類型都實現了
IEnumerable
接口或其泛型版本IEnumerable<T>
,以支持迭代和枚舉集合中的元素。這意味著它們都具有GetEnumerator()
方法,該方法返回一個實現了IEnumerator
接口或IEnumerator<T>
接口的對象,用于遍歷集合中的元素。
但是,并非所有集合都直接繼承自
IEnumerable
接口。例如,LinkedList<T>
繼承自System.Collections.Generic.LinkedList<T>
,而LinkedList<T>
實現了IEnumerable<T>
接口,但并未直接繼承自IEnumerable
。不過,由于IEnumerable<T>
繼承自IEnumerable
,因此LinkedList<T>
也間接地支持IEnumerable
。
總的來說,雖然不是所有集合都直接繼承自
IEnumerable
,但它們通常都實現了IEnumerable
接口或其泛型版本,以支持在foreach
循環中迭代集合中的元素。
在C#中,集合類型有很多種,每種都有其特定的使用環境和適用場景。
數組 (Array):
用于存儲固定大小的同類型元素。
適用于需要快速隨機訪問元素的情況。
int[] numbers = new int[5] { 1, 2, 3, 4, 5 };
列表 (List):
用于存儲可變大小的同類型元素序列。
適用于需要頻繁添加或刪除元素的場景。
List<string> names = new List<string>();
names.Add("Alice");
names.Add("Bob");
隊列 (Queue):
用于實現先進先出(FIFO)的數據結構。
適用于任務調度、消息傳遞等場景。
Queue<int> queue = new Queue<int>();
queue.Enqueue(1);
queue.Enqueue(2);
棧 (Stack):
用于實現后進先出(LIFO)的數據結構。
適用于表達式求值、深度優先搜索等場景。
Stack<string> stack = new Stack<string>();
stack.Push("A");
stack.Push("B");
字典 (Dictionary):
用于存儲鍵值對集合。
適用于需要快速通過鍵查找值的情況。
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Alice", 30);
ages.Add("Bob", 35);
集合 (Set):
用于存儲獨一無二的元素。
適用于需要去重或集合運算的場景。
HashSet<int> set = new HashSet<int>();
set.Add(1);
set.Add(2);
鏈表 (LinkedList):
用于存儲元素以節點形式組織的數據結構。
適用于頻繁的插入和刪除操作,但不適用于隨機訪問。
LinkedList<string> linkedList = new LinkedList<string>();
linkedList.AddLast("A");
linkedList.AddLast("B");
排序列表 (SortedList):
用于存儲已排序的鍵值對集合。
適用于需要快速查找和有序遍歷的場景。
SortedList<int, string> sortedList = new SortedList<int, string>();
sortedList.Add(3, "C");
sortedList.Add(1, "A");
有序字典 (SortedDictionary):
用于存儲已排序的鍵值對集合。
適用于需要有序鍵值對集合的場景。
SortedDictionary<int, string> sortedDictionary = new SortedDictionary<int, string>();
sortedDictionary.Add(3, "C");
sortedDictionary.Add(1, "A");
可觀察集合 (ObservableCollection):
用于實現數據綁定和通知變化的動態集合。
適用于需要與界面交互并實時更新的場景。
ObservableCollection<string> observableCollection = new ObservableCollection<string>();
observableCollection.Add("Item 1");
鍵控集合 (KeyedCollection):
用于存儲具有唯一鍵的元素集合。
適用于需要通過鍵進行查找和檢索的場景。
public class PersonCollection : KeyedCollection<string, Person>
{protected override string GetKeyForItem(Person item) => item.Name;
}
樹形集合 (Tree):
用于存儲具有層級結構的數據。
適用于表示組織結構、文件系統等場景。
// 示例:自定義樹形結構
public class TreeNode<T>
{public T Data { get; set; }public List<TreeNode<T>> Children { get; set; } = new List<TreeNode<T>>();
}
線程安全的集合
在多線程環境中,為了確保線程安全,可以使用以下線程安全的集合:
ConcurrentBag<T>
:用于在并行操作中存儲對象的無序集合。ConcurrentDictionary<TKey, TValue>
:用于在多線程環境中存儲鍵/值對的字典。ConcurrentQueue<T>
:用于在多線程環境中實現先進先出(FIFO)的隊列。ConcurrentStack<T>
:用于在多線程環境中實現后進先出(LIFO)的棧。BlockingCollection<T>
:提供了一個線程安全的集合,用于在生產者-消費者模式中使用。
這些線程安全的集合類型能夠在多線程環境中保證數據的一致性和完整性,避免出現競態條件和死鎖等問題。