带有Comparison委托的C#自定义比较器

本文关键字:自定义 比较器 Comparison 带有 | 更新日期: 2023-09-27 18:00:23

我正在尝试对自定义BindingList进行排序。但是我遇到了一个问题,我的比较器无法识别类的属性。无法识别"x.Code_PK_OriginalValue"。奇怪的是,intellisense在Comparer类中标记"Begrenzingen",与下面第一个代码块中的"Begrensingen"不同。

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);
    }
}

带有Comparison委托的C#自定义比较器

只使用lst.OrderBy(t => t.Code_PK_OriginalValue); 如何