如何排序列表< T>双价值? [英] How to sort a List<T> by double value?
本文介绍了如何排序列表< T>双价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这听起来似乎很简单,但并不多。
This sound simple but it not that much.
我要订购基于T,这是double类型的属性之一列表。
I want to order a List based on one of the properties of T, which is double type.
推荐答案
如果您知道在编译之前的PROPERTYNAME:
If you know the propertyname before compilation:
myList = myList.OrderBy(a=>a.propertyName).ToList();
或
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();
这篇关于如何排序列表< T>双价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文