[ACCEPTED]-Use reflection to make dynamic LINQ statements in C#-reflection

Accepted answer
Score: 40

You should use Expression Trees instead 6 of reflection. It will perform better, and 5 you'll be able to use it with both LINQ 4 to Objects and LINQ to SQL/Entities.

var source = new List<Test> { new Test { Id = 1, Name = "FirsT" }, new Test { Id = 2, Name = "Second" } };
var idName = "Id";
var idValue = 1;

var param = Expression.Parameter(typeof(Test));
var condition =
    Expression.Lambda<Func<Test, bool>>(
        Expression.Equal(
            Expression.Property(param, idName),
            Expression.Constant(idValue, typeof(int))
        ),
        param
    ).Compile(); // for LINQ to SQl/Entities skip Compile() call

var item = source.SingleOrDefault(condition);

then, you 3 can get Name property using reflection (you'll 2 do it just once, so it's fine to do it using 1 reflection.

var nameName = "Name";
var name = item == null ? null : (string) typeof(Test).GetProperty(nameName).GetValue(item);

Test class is defined as

public class Test
{
    public int Id { get; set; }
    public string Name { get; set; }
}
Score: 1

You can't use reflection, but you can use 4 dynamic Linq as described here. If you are 3 using Entity Framework for this, you should 2 also be able to use Entity SQL, which is 1 basically a hard-coded SQL string.

More Related questions