Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda "if" statement?

Tags:

c#

lambda

I have 2 objects, both of which I want to convert to dictionarys. I use toDictionary<>().

The lambda expression for one object to get the key is (i => i.name). For the other, it's (i => i.inner.name). In the second one, i.name doesn't exist. i.inner.name ALWAYS exists if i.name doesn't.

Is there a lambda expression I can use to combine these two? Basically to read as:

"if i.name exists then set id to i.name, else set id to i.inner.name".

Many thanks.

Update

When I say "don't exist", I mean the objects don't actually have the properties, not that the properties are just null.

like image 352
AndrewC Avatar asked Mar 19 '10 10:03

AndrewC


People also ask

Can lambda have if statement?

Using if else & elif in lambda function We can also use nested if, if-else in lambda function.

How do you do if else in lambda?

Using if, elif & else in Python lambda function Create a lambda function that accepts the number and returns a new number based on this logic, If the given value is less than 11, then return by multiplying it by 2. Else if it's between 11 to 22, then return, multiplying it by 3. Else returns the same un-modified value.

Can lambda function have multiple statements?

Yes. As alex's answer points out, sorted() is a version of sort that creates a new list, rather than sorting in-place, and can be chained.


3 Answers

If these are two distinct (reference) types then you can test them using the is or as keywords:

i => {
         var x = i as TypeThatHasNameProperty;
         return (x != null) ? x.name : i.inner.name;
     }

If you can't test for specific types then you can use reflection to test for the name property itself:

i => {
         var pi = i.GetType().GetProperty("name");
         return (pi != null) ? pi.GetValue(i, null) : i.inner.name;
     }
like image 133
LukeH Avatar answered Oct 12 '22 10:10

LukeH


Yes, the conditional operator ("ternary operator") does what you want:

(i => i.name != null ? i.name : i.inner.name)

Assuming, of course, that you can detect the "existence" of the name by checking for null.

Edit: In that case, Kirschstein's answer is better, of course.

like image 25
Thomas Avatar answered Oct 12 '22 11:10

Thomas


Why don't you give each object a ToDictionary method of their own, as they obviously have their own behaviours in this case.

If you can't add to the objects, because you don't own them, you can always write extension methods for them.

Any reason your trying to force feed them into one "common" function?

like image 35
Sekhat Avatar answered Oct 12 '22 11:10

Sekhat