如何通过double值对List <t>进行排序?</t>

时间:2010-01-25 22:26:23

标签: c# linq double linq-to-objects

这听起来很简单但不是那么多。

我想根据T的一个属性订购一个List,它是双重类型。

3 个答案:

答案 0 :(得分:5)

如果您在编译之前知道属性名称:

myList = myList.OrderBy(a=>a.propertyName).ToList();

myList = (from m in myList order by m.propertyName).ToList();

如果您在编译时没有该属性(例如,在网格中进行动态排序等);尝试以下扩展方法:

static class OrderByExtender
{
    public static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> collection, string key, string direction)
    {
        LambdaExpression sortLambda = BuildLambda<T>(key);

        if(direction.ToUpper() == "ASC")
            return collection.OrderBy((Func<T, object>)sortLambda.Compile());
        else
            return collection.OrderByDescending((Func<T, object>)sortLambda.Compile());
    }

    public static IOrderedEnumerable<T> ThenBy<T>(this IOrderedEnumerable<T> collection, string key, string direction)
    {
        LambdaExpression sortLambda = BuildLambda<T>(key);

        if (direction.ToUpper() == "ASC")
            return collection.ThenBy((Func<T, object>)sortLambda.Compile());
        else
            return collection.ThenByDescending((Func<T, object>)sortLambda.Compile());
    }

    private static LambdaExpression BuildLambda<T>(string key)
    {
        ParameterExpression TParameterExpression = Expression.Parameter(typeof(T), "p");
        LambdaExpression sortLambda = Expression.Lambda(Expression.Convert(Expression.Property(TParameterExpression, key), typeof(object)), TParameterExpression);
        return sortLambda;
    }
}

然后点击

myList = myList.OrderBy("propertyName", "ASC").ToList();

答案 1 :(得分:1)

var list = (from t in list
            orderby t.doubleVal).ToList();

答案 2 :(得分:0)

我认为这可以解决问题:

List<T> list = new List<T>();
//fill list here    
list.OrderBy(item => item.DoubleTypeProperty).ToList();

HTH