Converting dynamic type to dictionary C#

前端 未结 7 1243
执念已碎
执念已碎 2021-01-01 11:22

I have a dynamic object that looks like this,

 {
    \"2\" : \"foo\",
    \"5\" : \"bar\",
    \"8\" : \"foobar\"
 }

How can I convert this

7条回答
  •  攒了一身酷
    2021-01-01 12:16

    Very similar to ema answer, but with a one-liner using LINQ magic:

    Dictionary myDict = sourceObject.GetType().GetProperties().ToDictionary(prop => prop.Name, prop => prop.GetValue(sourceObject, null));
    

提交回复
热议问题