How to sort a List by double value?

后端 未结 3 403
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-01 07:35

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.

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-01 08:23

    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 OrderBy(this IEnumerable collection, string key, string direction)
        {
            LambdaExpression sortLambda = BuildLambda(key);
    
            if(direction.ToUpper() == "ASC")
                return collection.OrderBy((Func)sortLambda.Compile());
            else
                return collection.OrderByDescending((Func)sortLambda.Compile());
        }
    
        public static IOrderedEnumerable ThenBy(this IOrderedEnumerable collection, string key, string direction)
        {
            LambdaExpression sortLambda = BuildLambda(key);
    
            if (direction.ToUpper() == "ASC")
                return collection.ThenBy((Func)sortLambda.Compile());
            else
                return collection.ThenByDescending((Func)sortLambda.Compile());
        }
    
        private static LambdaExpression BuildLambda(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();
    

提交回复
热议问题