如何在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
我想按优先级类型,时间和顺序对此排序列表进行排序。我如何实现这一目标?
答案 0 :(得分:2)
创建自定义Comparer<myKey>
并将其传递给SortedList
constructor:
public class TypeComparer : Comparer<MyKey>
{
public override int Compare(MyKey x, MyKey y)
{
if (ReferenceEquals(x, y)) return 0;
int typeX = int.MinValue;
int typeY = int.MinValue;
if (x != null) typeX = x.type;
if (y != null) typeY = y.type;
return typeX.CompareTo(typeY);
}
}
现在您可以使用此构造函数:
var sl = new SortedList<MyKey, string>(new TypeComparer());
答案 1 :(得分:2)
C#中的SortedList使用IComparable接口对列表进行排序。因此,要实现这一点,您必须实现IComparable接口。请参阅:https://msdn.microsoft.com/en-us/library/system.icomparable.compareto(v=vs.110).aspx
一个例子:
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);
}
这写道:
测试
阿尔法
增量
答案 2 :(得分:1)
如果我理解正确:
.atc-style-glow-orange .atcb-link:hover {