使用对象作为SortedList的键<;对象,值>;在c#中
本文关键字:对象 gt SortedList 的键 lt | 更新日期: 2023-09-27 18:20:25
如何在c#中将Object定义为SortedList的Key。
在这里,我想定义一个像这样的关键对象
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
我想根据优先级类型、时间和顺序对这个排序列表进行排序。我该如何做到这一点?
例如:
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);
}
这写道:
β
α
Δ
创建一个自定义Comparer<myKey>
并将其传递给SortedList
构造函数:
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());
如果我理解正确:
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; }
}