首页 > 解决方案 > 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(),但在我的情况下,需要多个属性。

谢谢您的帮助!

标签: c#arrayslinqobject

解决方案


我建议从多维数组切换到数组数组——它更容易实现,并且很可能满足您在此任务中的所有需求。

这是您需要做的。假设您有一些具有一堆公共属性的通用类,您希望以这种方式序列化:

    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();

当然,itemsa在哪里。List<A>

就是这样。你有自己的数组数组。

如果你觉得你肯定需要它是一个 2D 数组,那么你必须像这里一样实现转换。


推荐阅读