Lambda “if” statement?

前端 未结 5 627
我寻月下人不归
我寻月下人不归 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 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;
         }
    

提交回复
热议问题