Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# multiple expression parameteres

Tags:

c#

lambda

linq

I'm trying to create a method signature that takes multiple properties of various type using

I would call it something like this:

AllPropertiesExcept(() => Property1, () => Property2)

This method almost work, except that the type of the properties have to be the same. I'm only going to use the property name, but want to use lambda expression to enable easy refactoring.

public static string MyMethod<T>(params Expression<Func<T>>[] propertyExpression)
like image 230
Karsten Avatar asked Feb 05 '26 08:02

Karsten


2 Answers

I would use AllPropertiesExcept(params Expression<Func<object>>[] properties), you can still get the property names out of it, but it doesn't matter what type the property is.

Edit: However, I would tend to use it the other way round - instead of excluding properties I don't want to see, I would include properties I want to see. The reason is simple - to make your way work, you still need reflection - with my way, you could easily use the Func you get to get the actual data directly.

Edit 2 (getting the property name out of an expression):

Expression<Func<object>> obj = something; // you get this in your method

((obj.Body as UnaryExpression).Operand as MemberExpression).Member.Name

I can really advise you to use LinqPad for such things, you can easily drill down objects via Dump(), which displays the objects very user friendly. Just recreate a small example and experiment.

like image 106
Femaref Avatar answered Feb 07 '26 22:02

Femaref


Does the method AllPropertiesExcept() return anything? Otherwise you could make a fluent interface (using method chaining):

AllPropertiesExcept(() => Property1)
    .And(() => Property2)
    .And(() => Property3);

Even if the AllPropertiesExcept() method returns something, you can defer the execution until you invoke a method at the end of the method chain:

var foo = AllPropertiesExcept(() => Property1)
    .And(() => Property2)
    .And(() => Property3)
    .DoSomeThing();
like image 30
Elian Ebbing Avatar answered Feb 07 '26 22:02

Elian Ebbing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!