How to sort a List<T> by double value?

大憨熊 提交于 2019-12-18 13:48:18

问题


This sound simple but it not that much.

I want to order a List based on one of the properties of T, which is double type.


回答1:


If you know the propertyname before compilation:

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

or

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

If you don't have the property at compile time (e.g. dynamic sorting in a grid or something); try the following extension methods:

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

Then order like

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



回答2:


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



回答3:


I think this sould do the trick:

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

HTH



来源:https://stackoverflow.com/questions/2136145/how-to-sort-a-listt-by-double-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!