在C#转换匿名类型成键/值数组? [英] In c# convert anonymous type into key/value array?

查看:939
本文介绍了在C#转换匿名类型成键/值数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下匿名类型:

 新{数据1 =测试1,DATA2 =萨姆,DATA3 =鲍勃}
 

我需要一种方法,将以此在,并输出密钥值对在阵列或字典​​。

我的目标就是用这个作为后数据的Htt的prequest,所以我最终将在串联成以下字符串:

 数据1 =测试1和放大器;数据2 =萨姆和放大器;数据3 =鲍勃
 

解决方案

这需要反思的只是一点点来完成。

  VAR一个=新{数据1 =测试1,DATA2 =萨姆,DATA3 =鲍勃};
VAR类型= a.GetType();
变种道具= type.GetProperties();
变种对= props.Select(X => x.Name +=+ x.GetValue(一,空))的ToArray()。
VAR的结果=的string.join(&放大器;对);
 

I have the following anonymous type:

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

I need a method that will take this in, and output key value pairs in an array or dictionary.

My goal is to use this as post data in an HttpRequest so i will eventually concatenate in into the following string:

"data1=test1&data2=sam&data3=bob"

解决方案

This takes just a tiny bit of reflection to accomplish.

var a = new { data1 = "test1", data2 = "sam", data3 = "bob" };
var type = a.GetType();
var props = type.GetProperties();
var pairs = props.Select(x => x.Name + "=" + x.GetValue(a, null)).ToArray();
var result = string.Join("&", pairs);

这篇关于在C#转换匿名类型成键/值数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆