20

If I have a LINQ statement like

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

how can I replace "id" and "name" with passed in variables using reflection? I keep getting object reference not set to instance of an object errors when I try. 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.

5
  • Sorry, I could not understand your problem or even your code :(. Could you remake the question body? Commented May 22, 2014 at 18:53
  • what is p in GetValue ? Commented May 22, 2014 at 18:53
  • a typo. should be o. Will edit. Commented May 22, 2014 at 18:54
  • What kind of LINQ is it? LINQ to Objects, LINQ to Entities, LINQ to SQL? Commented May 22, 2014 at 18:55
  • Try to specify BindingFlags.Instance | BindingFlags.Public as binding flags Commented May 22, 2014 at 19:00

2 Answers 2

47

You should use Expression Trees instead of reflection. It will perform better, and you'll be able to 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 Name property using reflection (you'll do it just once, so it's fine to do it using 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; }
}
Sign up to request clarification or add additional context in comments.

2 Comments

This works great. Just a tiny tweak to the code and it does what I wanted. Thank you.
@MarcinJuraszek This is EXACTLY what I was looking for. Thanks.
1

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

1 Comment

Maybe he could rewrite the lambda using expressions. But I am not sure of that he needs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.