c# - C# - 将对象列表转换为包含多个对象属性的数组
问题描述
我有这个 JSON 字符串:
{
"countries": [
{
"countryCode": "AR",
"country": "Argentina"
},
{
"countryCode": "BR",
"country": "Brazil"
}
]
}
这个 Country 类和国家列表:
List<Country> countries { get; set; }
class Country
{
public string country { get; set; }
public string countryCode { get; set; }
}
我需要创建一个包含国家代码和名称的二维对象数组:
propVal[0, 0] = "AR";
propVal[0, 1] = "Argentina";
propVal[1, 0] = "BR";
propVal[1, 1] = "Brazil";
.
.
.
现在我正在“手动”遍历国家列表并构建对象数组:
int row = 0;
foreach (Country country in countries)
{
propVal[row, 0] = country.countryCode;
propVal[row, 1] = country.country;
row++;
}
远景是有一个通用的方式,适用于其他 JSON,比方说 3 个或更多属性,并产生一个 x 维对象数组。有没有一种 LINQ 方法可以做到这一点?我知道这个线程,它处理一个对象属性并且 LINQ 方法是countries.Select(x=>x.country).ToArray()
,但在我的情况下,需要多个属性。
谢谢您的帮助!
解决方案
我建议从多维数组切换到数组数组——它更容易实现,并且很可能满足您在此任务中的所有需求。
这是您需要做的。假设您有一些具有一堆公共属性的通用类,您希望以这种方式序列化:
public class A
{
public string P1 {get; set;}
public string P2 {get; set;}
public string P3 {get; set;}
}
您可以像这样获取该类的属性集合:
var props = typeof(A).GetProperties();
然后,您需要做的就是对您的项目集合进行 LINQ 并获取每个属性的值:
var result = items.Select(item =>
props.Select(prop =>
prop.GetValue(item)
.ToString())
.ToArray())
.ToArray();
当然,items
a在哪里。List<A>
就是这样。你有自己的数组数组。
如果你觉得你肯定需要它是一个 2D 数组,那么你必须像这里一样实现转换。
推荐阅读
- pdo - 为什么这个 PDO 参数化查询表现得“奇怪”?
- python - 错误:float() 参数必须是字符串或数字,而不是 'dict_keys'
- python-3.x - 如果在 for 循环中连续发生两个异常,则执行某些操作
- wordpress - HTAccess 重定向 301 Wordpress 搜索结果
- python - Python中逗号分隔单词的正则表达式
- angular - ngrx createSelector TypeError 中的错误:无法读取未定义的属性“isOpen”
- php - 使用 UNION 在多个表中搜索但是当 ECHO 说未定义的变量时
- excel - 将 Google Chrome 窗口设置为变量
- google-apps-script - 聊天机器人如何提及尚未进入房间的用户?
- arrays - 将一个数组与另一个数组进行比较,然后返回匹配结果的索引