本文介绍了LINQ:如何在linq中动态使用ORDER BY,但仅当变量不是string.empty或null时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用LINQ2SQL,并且运行良好.但是,根据C#中变量类型字符串的值,我需要在查询中使用"Order By",或者不使用"order by".

I am using LINQ2SQL and its working pretty well. However depending on the value of the variable type string in C#, I need to use "Order By" in my query or not use an "order by".

如果C#字符串不是null或为空,那么我想对字符串变量的内容进行排序".如果C#字符串为空或为空,那么我不添加订单.

If the C# string is NOT null, or empty, then I want to "order by" on the contents of the string variable. If the C# string is empty or null, then I don't include an order by.

是否可以编写这种查询?

Is it possible to write this kind of query?

推荐答案

与VVS的答案类似,但如果要传递列名以进行订购,则可能要使用此扩展方法而不是内置的OrderBy方法:

Do like in VVS's answer, but if you want to pass in the column name for ordering you may want to use this extension method instead of the built-in OrderBy method:

public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> query, string memberName)  
{  
    ParameterExpression[] typeParams = new ParameterExpression[] { Expression.Parameter(typeof(T), "") };  

    System.Reflection.PropertyInfo pi = typeof(T).GetProperty(memberName);  

    return (IOrderedQueryable<T>)query.Provider.CreateQuery(  
        Expression.Call(  
            typeof(Queryable),  
            "OrderBy",  
            new Type[] { typeof(T), pi.PropertyType },  
            query.Expression,  
            Expression.Lambda(Expression.Property(typeParams[0], pi), typeParams))  
    );  
} 

这篇关于LINQ:如何在linq中动态使用ORDER BY,但仅当变量不是string.empty或null时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 16:22