C# 属性

C# 抽象

C# 字符串

C# 泛型

C# 杂项

C# 新特性

C# SortedList<TKey, TValue> 排序列表

C# SortedList<TKey, TValue> 是一个键/值对数组。它基于键存储值。SortedList<TKey, TValue> 类包含唯一键,并在键的基础上保持升序。借助 key,我们可以轻松地搜索或删除元素。它位于 System.Collections.Generic 命名空间中。

它就像 SortedDictionary<TKey, TValue> 类。

C# SortedList<TKey, TValue> vs SortedDictionary<TKey, TValue>

SortedList<TKey, TValue> 类使用的内存少于 SortedDictionary<TKey, TValue>。如果您必须存储和检索键/值对,建议使用 SortedList<TKey, TValue>。如果对未排序的数据执行插入和删除,SortedDictionary<TKey, TValue> 类比 SortedList<TKey, TValue> 类快。

C# SortedList<TKey, TValue> 示例

让我们看一个通用 SortedList<TKey, TValue> 类的示例,该类使用 Add() 方法存储元素并使用 for-each 循环迭代元素。在这里,我们使用 KeyValuePair 类来获取键和值。

例子 (Example)

using System;  
using System.Collections.Generic;  
  
public class SortedDictionaryExample  
{  
    public static void Main(string[] args)  
    {  
        SortedList<string, string> names = new SortedList<string, string>();  
        names.Add("1","Sonoo");    
        names.Add("4","Peter");    
        names.Add("5","James");    
        names.Add("3","Ratan");    
        names.Add("2","Irfan");    
        foreach (KeyValuePair<string, string> kv in names)  
        {  
            Console.WriteLine(kv.Key+" "+kv.Value);  
        }  
    }  
}

输出:

1 Sonoo
2 Irfan
3 Ratan
4 Peter
5 James


上一主题 C# SortedDictionary<TKey, TValue> 排序字典 下一主题 没有了
  • 使用社交账号登录,本站支持
全部评论(0)