c#如何选择数据结构

[ 2022-01-24 16:59:42 | 作者: admin ]
字号: | |
p.s.常用的数组


文章:常用数据结构及复杂度,必须看一看 https://www.cnblogs.com/gaochundong/p/3813252.html#!comments

Array (T[])
当元素的数量是固定的,并且需要使用下标时。
string[] news = new string[10]; //一维数组
string[,] news = new string[10,8]; //二维数组
int[][] numbers = { new int[] {2,3,4}, new int[] {5,6,7,8,9} }; //数组成员也是数组的情况

Linked list (LinkedList<T>)
当元素需要能够在列表的两端添加时。否则使用 List<T>。

Resizable array list (List<T>)
当元素的数量不是固定的,并且需要使用下标时。
List<T> 等同于同质的一维数组。它像 Array 一样可以快速的读取元素,还可以保持长度可变的灵活性。List<T> 内部同样使用 Array 来实现,但它隐藏了这些实现的复杂性。当创建 List<T> 时无需指定初始长度,当添加元素到 List<T> 中时,也无需关心数组大小的调整(resize)问题。
               // 创建 int 类型列表
               List<int> newsIds = new List<int>();
  
               // 创建 string 类型列表
               List<string> newsTitles = new List<string>();

Stack (Stack<T>)
当需要实现 LIFO(Last In First Out)时。

Queue (Queue<T>)
当需要实现 FIFO(First In First Out)时。

Hash table (Dictionary<TKey, TValue>)
当需要使用键值对(Key-Value)来快速添加和查找,并且元素没有特定的顺序时。
Hashtable 类是一个类型松耦合的数据结构,开发人员可以指定任意的类型作为 Key 或 Item。当 .NET 引入泛型支持后,类型安全的 Dictionary<K,T> 类出现。Dictionary<TKey, TValue> 使用强类型来限制 Key 和 Item,当创建 Dictionary<TKey, TValue> 实例时,必须指定 Key 和 Item 的类型。
通用例子:
Dictionary<keyType, valueType> variableName = new Dictionary<keyType, valueType>();
如果继续使用上面描述的社保号和员工的示例,我们可以创建一个 Dictionary<TKey, TValue> 的实例:
Dictionary<int, Employee> employeeData = new Dictionary<int, Employee>();
employeeData.Add(455110189) = new Employee("Scott Mitchell");
if (employeeData.ContainsKey(123456789))

Tree-based dictionary (SortedDictionary<TKey, TValue>)
当需要使用价值对(Key-Value)来快速添加和查找,并且元素根据 Key 来排序时。

Hash table based set (HashSet<T>)
当需要保存一组唯一的值,并且元素没有特定顺序时。

Tree based set (SortedSet<T>)
当需要保存一组唯一的值,并且元素需要排序时。
[最后修改由 admin, 于 2022-01-25 09:08:11]
评论Feed 评论Feed: http://blog.xg98.com/feed.asp?q=comment&id=2825

这篇日志没有评论。

此日志不可发表评论。