当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - LINQ: How to dynamically use an ORDER BY in linq but only if a variable is not string.empty or null

问题描述:

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".

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?

网友答案:

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))  
    );  
} 
网友答案:

Do it in two steps:

var query = from .. in .. where .. select ..;

if (!string.IsNullOrEmpty(someVariable))
{
    query = query.OrderBy((..) => ..);
}
网友答案:

Have C# test the contents of the list, and do the order only if it doesn't contain null.

var myList = (from s in dataContect.Users select s).ToList();

bool containsNull = false;

foreach (var item in mylist)
{
    if (string.IsNullOrEmpty(item.LastName))
    {
        containsNull = true;
    }
}

if (!containsNull)
{
    // If is not contains null, Use Order By
    myList = myList.OrderBy(k => k....);
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: