views:

26

answers:

2

Hi All,

I am using LINQ-to-Entities and here is my query

public void SomeFunction(string searchField)
{
var data = from a in dx.SomeTable where         
                a.SomeProperty="270"
                select a;
.
.
.

}

Now if I had to use the value of the parameter "searchField" as the property to be selected in the where clause then how do I do it ?

i.e I want to assign the value of the parameter "searchField" to the property I am checking in the where clause.

So ... the value of "SomeProperty" in a.SomeProperty must be the value of "searchField". How to do this ?

PS :

I dont want a.SomeProperty=searchField.

What I want is "SomeProperty" itself to be replaced by the value of "searchField" and then , this has to be checked to see if its equal to 270.

A: 

Scottgu posted how to do this a while ago: http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

Chris van de Steeg
I dug up the same solution on his blog ! thanks !
Sandeep
A: 

If the caller knows the type of your a (let's say it's MyType), I would suggest that you don't need dynamic LINQ - you can just pass in a predicate function:

public void SomeFunction(Func<MyType, bool> selector)
{
    // ...
    var data =  from a in dx.SomeTable
                where selector(a)
                select a;
}

// Calling code
SomeFunction(a => a.SomeProperty == "270");

Or if you want to keep the 270 value within SomeFunction, pass in a projection function to pull out SomeProperty :

public void SomeFunction(Func<MyType, string> propertyExtractor)
{
    // ...
    var data = from a in dx.SomeTable
               where propertyExtractor(a) == "270"
               select a;
}

// Calling code
SomeFunction(a => a.SomeProperty);

(apologies if this doesn't compile, am currently away from a compiler)

AakashM
Thanks Aakash I will try to check that out :)
Sandeep