是否可以在OrderBy标准中定义类型的使用方式

时间:2015-07-12 12:22:58

标签: c# linq

我有以下类型:

public class Type1
{
    public Int32 ID { get; set; }
    public Decimal Value { get; get; }
}

public class Type2
{
    public Int32 ID { get; set; }
    public Type1 Type1 { get; set; }
}

我还有以下功能:

List<Type2> GetOrderedType2List()    
{
    ...
    return type2List.OrderBy(type2 => type2.Type1).ToList();
}

我希望Type2列表的实例根据Type1值按其Type1.Value属性排序。但是,我想在Type1中编写代码,用于指定Type1条件中OrderBy的使用方式。

这可能吗?

感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

您需要实现IComparable,如下所示:

public class Type1 : IComparable
{
    public Int32 ID { get; set; }
    public Decimal Value { get; set; }

    public int CompareTo(object obj) {
        var castObj = obj as Type1;
        if (castObj == null)
            return -1;
        return Value.CompareTo(castObj.Value);
    }
}

测试:

var list = new List<Type2> { 
    new Type2 { Type1 = new Type1 { Value = 50 } }, 
    new Type2 { Type1 = new Type1 { Value = 2 } }, 
    new Type2 { Type1 = new Type1 { Value = 100 } }, 
    new Type2 { Type1 = new Type1 { Value = -10 } }
};

list.OrderBy(type2 => type2.Type1);

给出结果:

-10,2,50,100

或者,您可以选择仅与其他Type1对象进行比较(可能是最好的方法),并且可以这样做:

public class Type1 : IComparable<Type1>
{
    public Int32 ID { get; set; }
    public Decimal Value { get; set; }

    public int CompareTo(Type1 obj) {
        if (obj == null)
            return -1;
        return Value.CompareTo(obj.Value);
    }
}

答案 1 :(得分:0)

怎么样:

List<Type2> GetOrderedType2List()    
{
    ...
    return type2List.OrderBy(type2 => type2.Type1.Value).ToList();
}

答案 2 :(得分:0)

您可以按订单中定义的功能返回的值排序。我添加了一些随机逻辑,但你可以实现你想要的任何东西:

List<Type2> GetOrderedType2List()    
{
    ...
    return type2List.OrderBy(type2 =>
    {
        decimal orderValue;

        if (type2.Type1 == null)
            orderValue = 0;
        else if (type2.Type1.Value < 0)
            orderValue = Math.Abs(type2.Type1.Value);
        else
            orderValue = type2.Type1.Value;

        return orderValue;
    }).ToList();
}