个性化阅读
专注于IT技术分析

C#集合SortedList

点击下载

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

就像SortedDictionary <TKey,TValue>类。

C#SortedList <TKey,TValue>与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类获取键和值。

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
赞(0)
未经允许不得转载:srcmini » C#集合SortedList

评论 抢沙发

评论前必须登录!