C#SortedList<TKey,TValue>是键/值对的数组。它根据键存储值。SortedList<TKey,TValue>类包含唯一键,并根据键保持升序。在键的帮助下,无涯教程可以轻松地搜索或删除元素。它位于System.Collections.Generic命名空间中。
它类似于SortedDictionary<TKey、TValue>类。
SortedList<TKey,TValue>类比SortedDictionary<TKey,TValue>类使用的内存更少。如果必须存储和检索key/value对,建议使用SortedList<TKey、TValue>。如果对未排序的数据执行插入和删除,则SortedDictionary<TKey,TValue>类比SortedList<TKey,TValue>类更快。
让无涯教程看一个泛型SortedList<TKey,TValue>类的示例,该类使用add()方法存储元素,并使用for-each循环迭代元素。这里,使用KeyValuePair类来获取键和值。
using System; using System.Collections.Generic; public class SortedDictionaryExample { public static void Main(string[] args) { SortedListnames = new SortedList (); names.Add("1","Sonoo"); names.Add("4","Peter"); names.Add("5","James"); names.Add("3","Ratan"); names.Add("2","Irfan"); foreach (KeyValuePair kv in names) { Console.WriteLine(kv.Key+" "+kv.Value); } } }
输出:
1 Sonoo 2 Irfan 3 Ratan 4 Peter 5 James
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)
Python实战 · 从0到1搭建直播视频平台 -〔Barry〕