问题描述
我有一个复杂的问题,没有涉及太多细节.我只是想知道这是否可能.
I have a complex problem, without going into too many details. I'm just wondering if this is possible.
我有一个Ordered Linq查询,该查询获取数据的子集并将其推入DataTable.
I have an Ordered Linq query which gets a subset of data and pushes it into a DataTable.
var FormattedDataSet = DataSet.Select(t => new
{
ItemNumber = t.ExtTitleID,
Name = "<a href='/Title/Preview/" + t.ID + "'>" + t.TitleFullName + "</a>",
Master_Edited = t.MediaDetails.FirstOrDefault().Datecaptured
}).ToList();
Int是否可以根据匿名类型的声明的索引对此进行排序?
Is it Possible Int to sort this based on the index of the declaration of the Anonymous Type?
0 => ItemNumber
1 => Name
2 => MasterEdited
我需要能够做到这一点,而无需显式声明要进行排序的列名,因此,它对于任何匿名类型都可以通用.
I need to be able to do this with out explicitly declaring the column name to sort by, so this can work generically for any anonymous type.
推荐答案
我希望这还不算太晚,但是我为您准备了一些工作代码.我以前在项目中使用过它,并且没有引起任何明显的问题.
I hope this is not too late but I have some working code for you. I've used this in a project before and it hasn't caused any noticed problems.
public static IOrderedQueryable<T> OrderByPropertyDeclarionIndex<T>(this IQueryable<T> source, int propertyIndex, bool isDescending = false)
{
string OrderByText = isDescending ? "OrderByDescending" : "OrderBy";
return ApplyOrder(source, propertyIndex, OrderByText);
}
private static IOrderedQueryable<T> ApplyOrder<T>(IQueryable<T> source, int property, string methodName)
{
var type = typeof(T);
var arg = Expression.Parameter(type, "x");
Expression expr = arg;
var propertyinfos = type.GetProperties();
var pi = propertyinfos[property];
expr = Expression.Property(expr, pi);
type = pi.PropertyType;
var delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
var lambda = Expression.Lambda(delegateType, expr, arg);
var result = typeof(Queryable).GetMethods().Single(
method => method.Name == methodName
&& method.IsGenericMethodDefinition
&& method.GetGenericArguments().Length == 2
&& method.GetParameters().Length == 2)
.MakeGenericMethod(typeof(T), type)
.Invoke(null, new object[] { source, lambda });
return (IOrderedQueryable<T>)result;
}
这篇关于在匿名类型声明中按属性索引排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!