Comparer <t>。在.NET 4中创建

时间:2015-10-02 06:06:58

标签: c# .net-4.0

我在.Net 4.5中创建了一个Comparer:

public static Comparer<Room> RoomComparer = 
  Comparer<Room>.Create((a, b) => a.RoomId.CompareTo(b.RoomId))

如何在c#.NET 4.0中创建Comparer?

2 个答案:

答案 0 :(得分:8)

您可以使用以下

public static class Comparer
{
    public static Comparer<T> Create<T>(Comparison<T> comparison)
    {
        if (comparison == null) throw new ArgumentNullException("comparison");
        return new ComparisonComparer<T>(comparison);
    }
    private sealed class ComparisonComparer<T> : Comparer<T>
    {
        private readonly Comparison<T> comparison;
        public ComparisonComparer(Comparison<T> comparison)
        {
            this.comparison = comparison;
        }
        public override int Compare(T x, T y)
        {
            return comparison(x, y);
        }
    }
}
像这样

public static Comparer<Room> RoomComparer = 
  Comparer.Create<Room>((a, b) => a.RoomId.CompareTo(b.RoomId))

答案 1 :(得分:4)

public class RoomComparer: IComparer<Room>
{
    int Compare(Room a, Room b)  
    {
        return  (a == null && b == null) ? 0
            : (a == null) ? -1
            : (b == null) ? 1
            : a.RoomId.CompareTo(b.RoomId);
    }
}