C# 使用对象作为c中SortedList的键

C# 使用对象作为c中SortedList的键,c#,visual-studio,C#,Visual Studio,在c语言中,如何将对象定义为SortedList的键 这里我想定义一个像这样的关键对象 MyKey key = new MyKey(); key.type = 3; // can be 3,2 or 1 key.time = 2014-05-03 // DateTime in c# with timestamp key.sequence = 5567 // a number unique to the combination above 我想根据优先级类型、时间和顺序对

在c语言中,如何将对象定义为SortedList的键

这里我想定义一个像这样的关键对象

   MyKey key = new MyKey();
   key.type = 3; // can be 3,2 or 1
   key.time = 2014-05-03 // DateTime in c# with timestamp
   key.sequence = 5567 // a number unique to the combination above
我想根据优先级类型、时间和顺序对这个排序列表进行排序。我如何做到这一点

创建自定义并将其传递给:

现在您可以使用此构造函数:

var sl = new SortedList<MyKey, string>(new TypeComparer());

如果我理解正确:

static void Main(string[] args)
{
    Dictionary<MyKey, string> fooDictionary = new Dictionary<MyKey, string>();
    fooDictionary.Add(new MyKey() {FooNumber=1, Sequence=50 }, "1");
    fooDictionary.Add(new MyKey() { FooNumber = 2, Sequence = 40 }, "2");
    fooDictionary.Add(new MyKey() { FooNumber = 3, Sequence = 30 }, "3");
    fooDictionary.Add(new MyKey() { FooNumber = 4, Sequence = 20 }, "4");
    fooDictionary.Add(new MyKey() { FooNumber = 5, Sequence = 10 }, "5");
    var result = from c in fooDictionary orderby c.Key.Sequence select c;
    Console.WriteLine("");   
}

class MyKey
{
    public int FooNumber { get; set; }
    public DateTime MyProperty { get; set; }
    public int Sequence { get; set; }
}

C中的SortedList使用IComparable接口对列表进行排序。因此,要实现这一点,您必须实现IComparable接口。见:

例如:

public class Key : IComparable
{
    public int Type {get; set; }
    public DateTime Time { get; set; }
    public int Sequence { get; set; }

    int IComparable.CompareTo(object obj)
    {
        Key otherKey = obj as Key;
        if (otherKey == null) throw new ArgumentException("Object is not a Key!");

        if (Type > otherKey.Type)
            return 1;

       return -1;
    }
}
使用排序列表:

SortedList<Key,string> collection = new SortedList<Key, string>();

collection.Add(new Key { Type = 2 }, "alpha");
collection.Add(new Key { Type = 1 }, "beta");
collection.Add(new Key { Type = 3 }, "delta");

foreach (string str in collection.Values)
{
    Console.WriteLine(str);
}
这是这样写的:

贝塔

阿尔法

三角洲

SortedList<Key,string> collection = new SortedList<Key, string>();

collection.Add(new Key { Type = 2 }, "alpha");
collection.Add(new Key { Type = 1 }, "beta");
collection.Add(new Key { Type = 3 }, "delta");

foreach (string str in collection.Values)
{
    Console.WriteLine(str);
}