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

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 OrderBy(this IQueryable query, string memberName) { ParameterExpression typeParams = new ParameterExpression { Expression. Parameter(typeof(T), "") }; System.Reflection. PropertyInfo pi = typeof(T).

GetProperty(memberName); return (IOrderedQueryable)query.Provider. CreateQuery( Expression. Call( typeof(Queryable), "OrderBy", new Type { typeof(T), pi.

PropertyType }, query. Expression, Expression. Lambda(Expression.

Property(typeParams0, pi), typeParams)) ); }.

Excellent extension method! Thank you... I am putting in my tools right now :-) – Martin Nov 25 '10 at 16:28.

Do it in two steps: var query = from .. in .. where .. select ..; if (!string. IsNullOrEmpty(someVariable)) { query = query. OrderBy((..) => ..); }.

I think OP asking, any variable in query if null, then not order by. – Serkan Hekimoglu Nov 25 '10 at 10:16 @Serkan: "depending on the value of a variable of type string in c#" sounds to me as if the ordering depends on a single variable. – VVS Nov 25 '10 at 10:18 hmm yes you r right I think, sorry.

I wrote wrong answer then :) – Serkan Hekimoglu Nov 25 '10 at 10:24.

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....); }.

"linq: use to dynamically by" - Google Search.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions