c# - 通过编程 Linq/Lambda 创建订单

标签 c# .net linq c#-4.0 lambda

我有这段代码:

public void CreateOrdering(string field, string direction)
{
    //direction : ASC/DESC
    var result = context.MyTable
        .Where(x => x.Code > 5)
        .OrderBy()
        .Skip(10)
        .Take(5)
        .ToList<MyTable>();
}

我换个说法,我有一个方法,这个方法接收字符串字段名称用于排序和方向(“ASC”,“DESC”)

我想创建一个订单,其中包含参数中收到的字段和方向。我必须能够:

  1. 我希望在此查询中能够执行升序和降序
  2. 通过编程设置排序字段,这里的Code可以是后面的Id或者其他...
  3. 排序必须在 SQL Server 端完成,而不是在返回的列表上

谢谢,

最佳答案

您可以在允许 linq 语法的扩展方法中使用反射:

public static IQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, string field, string direction)
{
    string orderByMethod = (direction == "ASC") ? "OrderBy" : (direction == "DESC" ? "OrderByDescending" : null);
    if(orderByMethod == null) throw new ArgumentException();

    var propertyInfo = typeof (TSource).GetProperty(field);
    var entityParam = Expression.Parameter(typeof(TSource), "e");
    Expression columnExpr = Expression.Property(entityParam, propertyInfo);
    LambdaExpression columnLambda = Expression.Lambda(columnExpr, entityParam);

    MethodInfo orderByGeneric =  typeof (Queryable).GetMethods().Single(m => m.Name == orderByMethod
                                                    && m.GetParameters().Count() == 2
                                                    && m.GetParameters()[0].ParameterType.GetGenericTypeDefinition() == typeof(IQueryable<>)
                                                    && m.GetParameters()[1].ParameterType.GetGenericTypeDefinition() == typeof(Expression<>));

    MethodInfo orderBy = orderByGeneric.MakeGenericMethod(new [] {typeof(TSource), propertyInfo.PropertyType});

    return (IQueryable<TSource>) orderBy.Invoke(null, new object[] { source, columnLambda });
}

示例使用:

internal class SomeType
{
    public string StringValue { get; set; }
}

IQueryable<SomeType> l = new List<SomeType>
    {
        new SomeType {StringValue = "bbbbb"},
        new SomeType {StringValue = "cccc"},
        new SomeType {StringValue = "aaaa"},
        new SomeType {StringValue = "eeee"},
    }.AsQueryable();

var asc = l.OrderBy("StringValue", "ASC");
var desc = l.OrderBy("StringValue", "DESC");

或者你的例子:

context.MyTable
        .Where(x => x.Code > 5)
        .OrderBy(field, direction)
        .Skip(10)
        .Take(5)
        .ToList<MyTable>();

关于c# - 通过编程 Linq/Lambda 创建订单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12491145/

相关文章:

c# - 如何防止 WinForm 控件拉伸(stretch)并保持固定大小

c# - 如何对文件名进行编码以供下载?

.net - 通过Telegram机器人发送sendDocument

.NET Framework 4 ILASM 目标框架 2

c# - 如何根据运行总计在 Linq 中分组和/或选择

c# - 如何使用 LINQ 从列表列表输出由单个索引构造的整数列表?

c# - 如何在 XAML 文件中的 C# 和 Visual Studio 2010 中找到匹配的部分类?

c# - 如何读取字节和字符串的混合文件

c# - 如何以编程方式查找用于签署给定证书的证书?

c# - Linq - 在列表中按周分组