开发者

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 w开发者_如何学JAVArite 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....);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜