Use reflection to create dynamic LINQ statements in C #

If I have a LINQ statement, for example

x = Table.SingleOrDefault(o => o.id == 1).o.name; 

How to replace the words "id" and "name" with variables using reflection? When I try, I get a reference to an object that is not set to an instance of object errors. My attempts are things like

 x = (string)Table.SingleOrDefault(o => (int?)o.GetType().GetProperty(idString) .GetValue(o, null) == 1).GetType().GetField(nameString).GetValue(x); 

Any help would be great. Thanks.

+7
reflection c # linq
source share
2 answers

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(); // for LINQ to SQl/Entities skip Compile() call var item = source.SingleOrDefault(condition); 

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; } } 
+18
source share

You cannot use reflection, but you can use dynamic Linq, as described here . If you use the Entity Framework for this, you can also use Entity SQL, which is basically a hard-coded SQL string.

+1
source share

All Articles