C#有序列表

C#有序列表

一、引言

如果我们想要保存的是键-值对的数据的话,怎么处理呢?
我们可以创建一个键-值的两个参数的结构,然后将结构保存在集合中也是可以的。

例如下面的做法:

struct book<Tkey,Tvalue> //无论函数、类还是结构都只需在开始命名出加上<T>即可
{
    Tkey x;      //键
    Tvalue y;    //值

    public book(Tkey xx, Tvalue yy)  //构造函数无需加<T>
    {
        this.x = xx;
        this.y = yy;
    }
    public override string ToString()
    {
        return string.Format("书名为{0},价格为{1}", x, y);
    }
}
class Program
{
    static void Main(string[] args)
    {
        var myList = new List<book<string,string>>();

        myList.Add(new book<string,string>("C#入门","22"));
        myList.Add(new book<string,string>("WFC详解","33"));
        myList.Add(new book<string,string>("IP详解", "44"));

        Console.WriteLine(myList[0].ToString());
        
        Console.Read();
    }
}

通过上面的方法便可以实现键-值对的存储。那么我们有没有更加方便更加高效的办法来实现这种功能呢?
那就是“有序列表”

二、有序列表

SoredList<Tkey,Tvalue>有序列表专门正对需要存储键-值对的数据的。这个类按照键能给元素排序。其中Tkey和Tvalue都可以是任何类型。

public class SortedList<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IEnumerable

有序列表实现一中的功能如下:

var mySortedList = new SortedList<string, string>();
mySortedList.Add("C#入门", "22");
mySortedList.Add("WFC详解", "33");
mySortedList.Add("IP详解", "44");
mySortedList["计算机基础"] = "55";  //不存在的键,会新建添加到尾部
mySortedList["C#入门"] = "66";      //存在的键,会将原先的值覆盖

Console.WriteLine(mySortedList["计算机基础"]); //通过键的索引可以将值输出
foreach (KeyValuePair<string, string> books in mySortedList)
{
    Console.WriteLine(books);
}

foreach (string s in mySortedList.Keys)   //可统一的将所有的键输出
{
    Console.WriteLine(s);
}

foreach (string s in mySortedList.Values)  //可统一的将所有的值输出
{
    Console.WriteLine(s);
}

总体来说有序列表比较强大,此外它还可以排序。
上述代码执行结果可以看出,输出的结果都是排序好的。所以有序列表在添加元素时就会自动的进行排序了。

三、有序列表的常用方法

有序列表常用方法如下:

在这里插入图片描述

发布了50 篇原创文章 · 获赞 0 · 访问量 859

猜你喜欢

转载自blog.csdn.net/weixin_40786497/article/details/104158279