C#Custom Comparer with Comparison委托

时间:2011-06-23 08:26:36

标签: c# delegates comparison

我正在尝试对自定义BindingList进行排序。但我遇到的问题是我的Comparer无法识别我班级的属性。 无法识别“x.Code_PK_OriginalValue”。奇怪的是,intellisense在Comparer类中标记“Begrenzingen”,在下面的第一个代码块中标记为“Begrenzingen”。

BindingListX<Begrenzingen> lst = new BindingListX<Begr.....;

lst.OrderBy(t => t, new CustomComparer<Begrenzingen>());

public class CustomComparer<Begrenzingen> : IComparer<Begrenzingen>
{
    private readonly Comparison<Begrenzingen> _comparison;

    public CustomComparer()
    {
        _comparison = new Comparison<Begrenzingen>(
                            (Begrenzingen x, Begrenzingen y) =>
                            {
                                return x.Code_PK_OriginalValue.CompareTo(y.Code_PK_OriginalValue);
                            }
                      );
    }

    public int Compare(Begrenzingen x, Begrenzingen y)
    {
        return _comparison(x, y);
    }
}

public class BindingListX<T> : BindingList<T>
{
    public void OrderBy(Func<T,T> keySelector, IComparer<T> comparer)
    {
        this.Items.OrderBy(keySelector, comparer);
    }
}

public class Begrenzingen : DefaultTable, IComparable<Begrenzingen>
{
    public Begrenzingen()
    { //New -> Insert DB
        Code_PK_OriginalValue = -1;
        isDeleted = false;
    }

    public decimal Code_PK_OriginalValue { get; set; }
    public decimal Code_PK { get; set; }
    public string Naam { get; set; }
    public decimal? SeqLayer { get; set; }

    public Boolean isDeleted { get; set; }

    public string SeqLayerDisplayValue { 
        get {
            if (SeqLayer == null) return string.Empty;
            return (from sdo in MainWindow.Main.SdoLayers where sdo.SeqLayer == this.SeqLayer select sdo.DisplayValue).First();
        } 
    }


    public override string ToString()
    {
        return String.Format("{0};{1};{2};{3}", Code_PK_OriginalValue, Code_PK, Naam, SeqLayer);
    }

    public int CompareTo(Begrenzingen o)
    {
        return Code_PK.CompareTo(o.Code_PK);
    }
}

1 个答案:

答案 0 :(得分:1)

lst.OrderBy(t => t.Code_PK_OriginalValue);

怎么样?