我有一个列表,其中元素是:
struct element {
double priority;
int value;
}
如何实现我自己的比较器,允许我按优先级排序列表?我尝试使用 SortredList ......但它不允许重复键:(
非常感谢您的帮助!
我有一个列表,其中元素是:
struct element {
double priority;
int value;
}
如何实现我自己的比较器,允许我按优先级排序列表?我尝试使用 SortredList ......但它不允许重复键:(
非常感谢您的帮助!
假设 C# 3 或更高版本:
var sorted = MyList.OrderBy(e => e.priority);
您可以使用接受委托的Sort
重载来执行就地排序:Comparison<T>
yourList.Sort((x, y) => x.priority.CompareTo(y.priority));
对于旧版本的 C#,您需要将 lambda 替换为老式委托语法:
yourList.Sort(
delegate(element x, element y) { return x.priority.CompareTo(y.priority); });
如果您不能依赖 C# 3 扩展或 Lambda,那么您可以让您的结构实现IComparable接口,如下所示:
struct element : IComparable
{
double priority;
int value;
public element(int val, double prio)
{
priority = prio;
value = val;
}
#region IComparable Members
public int CompareTo(object obj)
{
// throws exception if type is wrong
element other = (element)obj;
return priority.CompareTo(other.priority);
}
#endregion
}
这个接口也有类型安全的版本,但是原理是一样的
在结构或类上实现该接口后,调用Sort方法List<>
将“正常工作”
static void Main(string[] args)
{
Random r = new Random();
List<element> myList = new List<element>();
for (int i = 0; i < 10; i++)
myList.Add(new element(r.Next(), r.NextDouble()));
// List is now unsorted
myList.Sort();
// List is now sorted by priority
Console.ReadLine();
}
这取决于您是要对列表本身进行排序,还是按排序顺序检索值(不更改列表)。
对列表本身进行排序(假设你有一个List<element>
被调用的elements
):
elements.Sort((x, y) => x.priority.CompareTo(y.priority));
// now elements is sorted
.NET 2.0 等效:
elements.Sort(
delegate(element x, element y) {
return x.priority.CompareTo(y.priority);
}
);
要按排序顺序获取值:
var orderedElements = elements.OrderBy(x => x.priority);
// elements remains the same, but orderedElements will retrieve them in order
.NET 2.0 中没有等效的 LINQ,但您可以编写自己的:
public static IEnumerable<T> OrderBy<T>(IEnumerable<T> source, Comparison<T> comparison) {
List<T> copy = new List<T>(source);
copy.Sort(comparison);
foreach (T item in copy)
yield return item;
}
用法:
Comparison<element> compareByPriority = delegate(element x, element y) {
return x.priority.CompareTo(y.priority);
};
// unfortunately .NET 2.0 doesn't support extension methods, so this has to be
// expressed as a regular static method
IEnumerable<element> orderedElements = OrderBy(elements, compareByPriority);
如果您想在不创建新实例的情况下对列表本身进行排序,您可以实现 IComparer,然后使用您的实现实例调用 List.Sort
public class ElementComparer : IComparer<element>
{
public int Compare(element x, element y)
{
throw new NotImplementedException();
}
}