How to sort list <T> by double value?

This sound is simple, but it is not so much.

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

0
source share
3 answers

If you know the name of the property before compilation:

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

or

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

If you do not have a property at compile time (for example, dynamic sorting in a grid or something else); 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 the order is kind of

 myList = myList.OrderBy("propertyName", "ASC").ToList(); 
+5
source
 var list = (from t in list orderby t.doubleVal).ToList(); 
+1
source

I think this might do the trick:

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

NTN

0
source

Source: https://habr.com/ru/post/1299571/


All Articles