做一个营销型网站多少钱,企业官网制作费用,软件开发公司排名,深圳小程序开发方案一、C# 集合概述C# 中的集合是用于存储和管理一组相关对象的特殊类#xff0c;它们提供了比数组更强大的功能#xff0c;如动态大小调整、排序、搜索等。二、集合的主要种类1. 非泛型集合 (System.Collections)// 已过时#xff0c;不推荐在新项目中使用
ArrayList list ne…一、C# 集合概述C# 中的集合是用于存储和管理一组相关对象的特殊类它们提供了比数组更强大的功能如动态大小调整、排序、搜索等。二、集合的主要种类1.非泛型集合 (System.Collections)// 已过时不推荐在新项目中使用 ArrayList list new ArrayList(); list.Add(1); // 可以添加任何类型 list.Add(string); // 类型不安全2.泛型集合 (System.Collections.Generic)-推荐使用列表类集合// ListT - 最常用的动态数组 Liststring fruits new Liststring { Apple, Banana, Orange }; fruits.Add(Mango); fruits.Remove(Banana); // LinkedListT - 双向链表 LinkedListint numbers new LinkedListint(); numbers.AddLast(1); numbers.AddFirst(0); // ObservableCollectionT - 支持数据绑定和通知 ObservableCollectionstring items new ObservableCollectionstring(); items.CollectionChanged (sender, e) { Console.WriteLine(集合已更改); };字典类集合// DictionaryTKey, TValue - 哈希表实现的键值对 Dictionarystring, int ages new Dictionarystring, int { [Alice] 25, [Bob] 30 }; ages[Charlie] 28; // SortedDictionaryTKey, TValue - 基于二叉搜索树的有序字典 SortedDictionaryint, string sortedDict new SortedDictionaryint, string(); // ConcurrentDictionaryTKey, TValue - 线程安全的字典 ConcurrentDictionarystring, int concurrentDict new ConcurrentDictionarystring, int();队列和栈// QueueT - 先进先出(FIFO) Queuestring queue new Queuestring(); queue.Enqueue(First); queue.Enqueue(Second); string firstItem queue.Dequeue(); // StackT - 后进先出(LIFO) Stackint stack new Stackint(); stack.Push(1); stack.Push(2); int topItem stack.Pop();集合类// HashSetT - 不包含重复元素的高性能集合 HashSetint uniqueNumbers new HashSetint { 1, 2, 2, 3 }; // 结果: 1, 2, 3 // SortedSetT - 有序的不重复集合 SortedSetstring sortedSet new SortedSetstring(); // ReadOnlyCollectionT - 只读集合包装器 IReadOnlyListstring readOnlyList fruits.AsReadOnly();不可变集合 (System.Collections.Immutable)// 线程安全且不可变的集合 ImmutableListstring immutableList ImmutableList.Create(A, B, C); ImmutableDictionarystring, int immutableDict ImmutableDictionary.Createstring, int();三、集合的遍历方式1.foreach 循环 (推荐)foreach (var fruit in fruits) { Console.WriteLine(fruit); } // 遍历字典 foreach (KeyValuePairstring, int kvp in ages) { Console.WriteLine(${kvp.Key}: {kvp.Value}); }2.for 循环 (适用于需要索引的情况)for (int i 0; i fruits.Count; i) { Console.WriteLine($索引 {i}: {fruits[i]}); }四、常见用法示例1.集合初始化// 多种初始化方式 Listint numbers1 new Listint { 1, 2, 3 }; Listint numbers2 new() { 1, 2, 3 }; // C# 9.0 var numbers3 new Listint { 1, 2, 3 }; // 字典初始化 var dict1 new Dictionarystring, int { { Alice, 25 }, { Bob, 30 } }; var dict2 new Dictionarystring, int { [Alice] 25, [Bob] 30 };2.集合操作// 添加元素 fruits.Add(Grape); fruits.AddRange(new[] { Peach, Pear }); fruits.Insert(1, Lemon); // 删除元素 fruits.Remove(Apple); fruits.RemoveAt(0); fruits.RemoveAll(f f.StartsWith(A)); // 查找元素 bool hasApple fruits.Contains(Apple); int index fruits.IndexOf(Banana); var apple fruits.Find(f f Apple); // 排序 fruits.Sort(); fruits.Sort((x, y) x.Length.CompareTo(y.Length)); // 转换数组 string[] fruitArray fruits.ToArray(); Liststring fruitList fruitArray.ToList();3.性能优化操作// 预设容量提升性能 Liststring largeList new Liststring(10000); // 批量操作 Listint source Enumerable.Range(1, 10000).ToList(); Listint destination new Listint(source.Count); destination.AddRange(source);五、重要注意事项1.集合选择指南选择原则 - 需要快速随机访问 → ListT - 频繁插入/删除 → LinkedListT - 键值对存储 → DictionaryTKey, TValue - 需要排序 → SortedDictionaryTKey, TValue - 去重 → HashSetT - 线程安全 → ConcurrentBag/Queue/Stack/Dictionary - 只读 → ReadOnlyCollectionT - 不可变 → ImmutableList/Dictionary2.遍历时修改集合的陷阱// 遍历时直接修改会抛出InvalidOperationException foreach (var fruit in fruits) { if (fruit Apple) fruits.Remove(fruit); // 运行时错误 } // 正确做法1使用ToArray()副本 foreach (var fruit in fruits.ToArray()) { if (fruit Apple) fruits.Remove(fruit); } // 正确做法2使用for循环反向遍历 for (int i fruits.Count - 1; i 0; i--) { if (fruits[i] Apple) fruits.RemoveAt(i); } // 正确做法3先标记后删除 var itemsToRemove new Liststring(); foreach (var fruit in fruits) { if (fruit Apple) itemsToRemove.Add(fruit); } foreach (var item in itemsToRemove) { fruits.Remove(item); }3.字典使用注意事项Dictionarystring, int dict new Dictionarystring, int(); // 错误访问不存在的键 int value dict[nonexistent]; // KeyNotFoundException // 正确使用TryGetValue if (dict.TryGetValue(Alice, out int age)) { Console.WriteLine(age); } // 正确使用ContainsKey检查 if (dict.ContainsKey(Alice)) { value dict[Alice]; } // 字典键的自定义类型需要正确实现GetHashCode和Equals public class Person { public string Name { get; set; } public override bool Equals(object obj) obj is Person other Name other.Name; public override int GetHashCode() Name?.GetHashCode() ?? 0; }4.性能注意事项// ListT的容量管理 Listint list new Listint(); for (int i 0; i 1000; i) { list.Add(i); // 多次重新分配内存 // 如果知道大小预设容量 Listint optimizedList new Listint(1000); } // HashSetT vs ListT的Contains性能 HashSetstring hashSet new HashSetstring(); // O(1) Liststring normalList new Liststring(); // O(n)5.线程安全// 非线程安全 Liststring unsafeList new Liststring(); // 使用锁 object lockObj new object(); lock (lockObj) { unsafeList.Add(item); } // 使用并发集合 ConcurrentBagstring safeBag new ConcurrentBagstring(); safeBag.Add(item);6.内存管理// 及时清理不再使用的集合 Listbyte[] largeData new Listbyte[](); // 使用后清理 largeData.Clear(); largeData.TrimExcess(); // 释放多余容量 // 使用using语句处理需要释放资源的集合 using (BlockingCollectionint collection new BlockingCollectionint()) { // 使用集合 }7.空值处理// 处理可能的null集合 Liststring possibleNullList GetList(); var count possibleNullList?.Count ?? 0; // 安全访问 // 使用空集合代替null public Liststring GetItems() { return new Liststring(); // 而不是返回null }六、总结优先使用泛型集合避免非泛型集合根据场景选择合适的集合类型遍历时避免修改集合内容合理预设集合容量提升性能及时释放不再使用的集合