Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access property in lambda expression from string when using LINQ

How can I do something like this:

var result = db.MyTable.Where(x => x."MyProperty" == "Test" );

As you can see I want to access "MyProperty" but give the property name as a sting.

like image 440
NKnusperer Avatar asked Aug 10 '11 20:08

NKnusperer


People also ask

Can you use LINQ on a string?

LINQ can be used to query and transform strings and collections of strings. It can be especially useful with semi-structured data in text files. LINQ queries can be combined with traditional string functions and regular expressions. For example, you can use the String.

Can you use Lambda expression instead of LINQ query?

So performance-wise, there's no difference whatsoever between the two. Which one you should use is mostly personal preference, many people prefer lambda expressions because they're shorter and more concise, but personally I prefer the query syntax having worked extensively with SQL.

Which is faster LINQ or lambda?

There is no performance difference between LINQ queries and Lambda expressions.


1 Answers

You could use reflection

x.GetType( ).GetProperty("MyProperty").GetValue( x, null ); 

although this might work, i wouldn't advise on doing this, why don't pass in your where clause as an expression like:

myMethod<T>(Expression<Func<T,bool>> where)

example after comment:

consider the following type:

you see there are three properties where the name is of type string and id is of type int. now if we wrap our database context in a service like this

public class MyTypeOfXService
{
    private DataDataContext Context;
    public MyTypeOfXService()
    {
        Context = new DataDataContext("example code");
    }

    public IQueryable<MyTypeOfX> GetTypeOfX(Expression<Func<MyTypeOfX, bool>> where)
    {
        return this.Context.MyTypeOfXes.Where(where);
    }
}

in our get method there is an Expression parameter that takes two generics, the first is our type x and the second is a boolean. The advantage of this approach is that we can abstract all the data context creation and only express an where clause in our code see final piece of code:

class Program
{
    static void Main(string[] args)
    {
        var service = new MyTypeOfXService();

        var queryById = service.GetTypeOfX((mytype) => mytype.Id == 1);
        var queryByName = service.GetTypeOfX((mytype) => mytype.Name == "MyName");
        var queryByName = service.GetTypeOfX((mytype) => mytype.Name == "MyName" && mytype.Id == 1);
    }
}

as you can see, we can build a where clause on any property or combination of properties.

like image 133
Didier Caron Avatar answered Oct 10 '22 06:10

Didier Caron