如何使用IComparable接口? [英] How do I use the IComparable interface?
本文介绍了如何使用IComparable接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一个有关如何使用 IComparable
接口的基本示例,以便我可以按升序或降序以及要排序的对象类型的不同字段进行排序.
I need a basic example of how to use the IComparable
interface so that I can sort in ascending or descending order and by different fields of the object type I'm sorting.
推荐答案
好吧,因为您使用的是 List< T>
,所以仅使用 Comparison< T>;
,例如:
Well, since you are using List<T>
it would be a lot simpler to just use a Comparison<T>
, for example:
List<Foo> data = ...
// sort by name descending
data.Sort((x,y) => -x.Name.CompareTo(y.Name));
当然,有了LINQ,您可以使用:
Of course, with LINQ you could just use:
var ordered = data.OrderByDescending(x=>x.Name);
但是您可以很容易地在 List< T>
中重新引入(用于就地重新排序);这是一个允许使用lambda语法对 List< T>
进行 Sort
的示例:
But you can re-introduce this in List<T>
(for in-place re-ordering) quite easily; Here's an example that allows Sort
on List<T>
with lambda syntax:
using System;
using System.Collections.Generic;
class Foo { // formatted for vertical space
public string Bar{get;set;}
}
static class Program {
static void Main() {
List<Foo> data = new List<Foo> {
new Foo {Bar = "abc"}, new Foo {Bar = "jkl"},
new Foo {Bar = "def"}, new Foo {Bar = "ghi"}
};
data.SortDescending(x => x.Bar);
foreach (var row in data) {
Console.WriteLine(row.Bar);
}
}
static void Sort<TSource, TValue>(this List<TSource> source,
Func<TSource, TValue> selector) {
var comparer = Comparer<TValue>.Default;
source.Sort((x,y)=>comparer.Compare(selector(x),selector(y)));
}
static void SortDescending<TSource, TValue>(this List<TSource> source,
Func<TSource, TValue> selector) {
var comparer = Comparer<TValue>.Default;
source.Sort((x,y)=>comparer.Compare(selector(y),selector(x)));
}
}
这篇关于如何使用IComparable接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文