Lambda “if” statement?

前端 未结 5 629
我寻月下人不归
我寻月下人不归 2021-02-04 13:36

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 th

相关标签:
5条回答
  • 2021-02-04 13:48

    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.

    0 讨论(0)
  • 2021-02-04 13:52

    something along the lines of

    collection1.ForEach(i => myDictionary.Add((i.name.length == 0 ? i.inner.name : i.name),value);
    

    (untested) should do the trick if i.name is not null (an empty string), or

    collection1.ForEach(i => myDictionary.Add((i.name ?? i.inner.name),value);
    

    (also untested)

    0 讨论(0)
  • 2021-02-04 14:00

    as an inline if query I would use a ternary operator, so:

    (i.name != null ? set id to i.name : set id to i.inner.name)
    
    0 讨论(0)
  • 2021-02-04 14:09

    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?

    0 讨论(0)
  • 2021-02-04 14:10

    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;
         }
    
    0 讨论(0)
提交回复
热议问题