DCSIMG
Cool LINQ trick - Ariel's Remote Data Center

Cool LINQ trick

Posted Dec 22 2008, 07:31 PM by Ariel Ben Horesh  

Today I was approached with a nice question.

Suppose we have a simple class with a few properties.

image

We want to do a linq query over it with a where clause. (it doesn’t matter what is the data source, in this case it will be plain CLR objects).

Let’s say that we want to construct our Where clause in such a matter that if a variable is null we ignore it and use another condition, but if it is not null we will use this one; did I confuse you?

let’s try to look on an example:

First we will create our “DataSource”. For our example just a list of Margols.

List<Margol> list = new List<Margol> 
{   new Margol { Name="x", Address="y", Val=0}, 
    new Margol { Name = "a", Address="b", Val=1}
};

Let’s mock some variables we want to filter our list with them:

string nameCheck = null;
int valueCheck = 0;

and now let’s create a simple query:

var d = (from m in list
         where m.Name == nameCheck
         select m);

The problem is that if nameCheck is null we will get an exception, furthermore we would like that if it is the case make fallback condition with valueCheck based that fact. (Thus a simple check is not enough).

Anyway it is a cool excuse to check out a different approach.

First we will not use the syntactic shortcuts and we will use the extensions methods.

We will exchange that query with that one:

var d = list.Where(myMethod).Select(m => m);

Only thing now for us is to declare myMethod.

myMethod will be a function that gets a Margol as a parameter and will return a bool, meaning whether it will be filtered or not, and now we have all the power of the world! to do whatever we want.

 

Func<Margol, bool> myMethod =
               m =>
               {
                   if (nameCheck != null)
                   {
                       return (m.Name == nameCheck);
                   }
                   else
                   {
                       return (m.Val == valueCheck);
                   }
               };

 

Cheers,

Ariel

תגים:, , ,



Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: