开发者

How to use a parameters value as the property to be selected in a LINQ Query?

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开发者_如何学Go 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.


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


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)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜