问题
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?
回答1:
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))
);
}
回答2:
Do it in two steps:
var query = from .. in .. where .. select ..;
if (!string.IsNullOrEmpty(someVariable))
{
query = query.OrderBy((..) => ..);
}
回答3:
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....);
}
来源:https://stackoverflow.com/questions/4275878/linq-how-to-dynamically-use-an-order-by-in-linq-but-only-if-a-variable-is-not-s