Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to pass a list of property names as Lambda Expressions

Tags:

c#

.net

lambda

I have a class MyDummyClass to which I'd like to pass some properties in form of a Lambda expression for a later evaluation. So what I can do something like

public class MyDummyClass<T>
{
    public MyDummyClass(Expression<Func<T, object>> property)
    {
        ...
    }
    ...
}

..and then use that class like new MyDummyClass<Person>(x=>x.Name), right?

But then I'd like to pass not only a single property but a list of properties. So I'd write my class like

public class MyDummyClass<T>
{
    public MyDummyClass(IEnumerable<Expression<Func<T, object>>> properties)
    {
        ...
    }
    ...
}

and I'd like to use it like new MyDummyClass<Person>(new[] { x=>x.Name, x=>x.Surname }) but unfortunately that doesn't work! Instead I have to write

new MyDummyClass<Person>
     (new Expression<Func<Person, object>>[] { x=>x.Name, x=>x.Surname});

But this is a bit awkward to write, isn't it? Of course, using params would work, but this is just a sample out of a more complicated piece of code where using params is not an option. Does anyone have a better option to come out of this??

like image 986
Juri Avatar asked Feb 02 '23 08:02

Juri


1 Answers

Try using params instead:

public MyDummyClass(params Expression<Func<T, object>>[] properties)

Then you should be able to do:

var dummy = new DummyClass<Person>(x => x.Name, x => x.Surname);
like image 157
Trevor Pilley Avatar answered Feb 05 '23 04:02

Trevor Pilley