You should use expression trees instead of reflection. It will work better and you can use it with both LINQ 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();
then you can get the Name property with reflection (you will do it only once, so itβs great if you do it with 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; } }
MarcinJuraszek
source share