In c# convert anonymous type into key/value array?

前端 未结 9 1448
囚心锁ツ
囚心锁ツ 2020-12-04 23:28

I have the following anonymous type:

new {data1 = \"test1\", data2 = \"sam\", data3 = \"bob\"}

I need a method that will take this in, and

9条回答
  •  抹茶落季
    2020-12-04 23:50

    It is too late but anyway I would add this for a more robust solution. The ones I see here have some kind of problems (like they wouldn't work right with say DateTime). For that reason, I suggest first converting to a json (Newtonsoft Json.Net):

    var data = new {data1 = "test1", data2 = "sam", data3 = "bob"};
    
    var result = string.Join("&",
                JsonConvert.DeserializeObject>(
                JsonConvert.SerializeObject(data))
                .Select(x => $"{x.Key}={x.Value}")
            );
    

提交回复
热议问题