group by json对象共享密钥名称

时间:2017-07-10 06:44:31

标签: c# linq

public class NameDTO
{
    public string Name;
}

public class ValDTO
{
    public string Val;
}

_nameDetials = new List<NameDTO>();
_valDetials = new List<ValDTO>();  

进入List _nameDetials我得到键并进入_valDetails我得到了我在下面用于块的值并将它们添加到数组中。在下面的给定值中,我将每个列表计为20。

JArray jChildArray = new JArray();      

for (int i = 0; i < Math.Max(_nameDetials.Count, _valDetials.Count); i++)
{
    JObject jChildObject = new JObject();    
    jChildObject.Add(_nameDetials[i].Name, _valDetials[i].Val);    
    jChildArray.Add(jChildObject);                                                  
}

我有一个json数组,如下所示

[
  {
    "message-Code": "   0"
  },
  {
    "msg-Number-Pos1": "0"
  },
  {
    "msg-Number-Pos2": "0"
  },
  {
    "msg-Number-Pos3": " "
  },
  {
    "message-Code": "   0"
  },
  {
    "msg-Number-Pos1": "0"
  },
  {
    "msg-Number-Pos2": "0"
  },
  {
    "msg-Number-Pos3": " "
  },
  {
    "message-Code": "   0"
  },
  {
    "msg-Number-Pos1": "0"
  },
  {
    "msg-Number-Pos2": "0"
  },
  {
    "msg-Number-Pos3": " "
  },
  {
    "message-Code": "   0"
  },
  {
    "msg-Number-Pos1": "0"
  },
  {
    "msg-Number-Pos2": "0"
  },
  {
    "msg-Number-Pos3": " "
  },
  {
    "message-Code": "   0"
  },
  {
    "msg-Number-Pos1": "0"
  },
  {
    "msg-Number-Pos2": "0"
  },
  {
    "msg-Number-Pos3": "0"
  }
]

我想将此数据分组以获得如下所示的结果。

[
    {
      "message-Code": "  0",
      "msg-Number-Pos1": "0",
      "msg-Number-Pos2": "0",
      "msg-Number-Pos3": "0"
    },
    {
      "message-Code": "  0",
      "msg-Number-Pos1": "0",
      "msg-Number-Pos2": "0",
      "msg-Number-Pos3": "0"
    },
    {
      "message-Code": "  0",
      "msg-Number-Pos1": "0",
      "msg-Number-Pos2": "0",
      "msg-Number-Pos3": "0"
    },
    {
      "message-Code": "  0",
      "msg-Number-Pos1": "0",
      "msg-Number-Pos2": "0",
      "msg-Number-Pos3": "0"
    },
    {
      "message-Code": "  0",
      "msg-Number-Pos1": "0",
      "msg-Number-Pos2": "0",
      "msg-Number-Pos3": "0"
    }
]

我想基于相同的键名进行分组。

我尝试了以下代码

var grouparray = (from t in jChildArray
                  group t by new { t }
                  into grp
                  select grp.Key.t).ToList();

我无法追踪我遗漏的内容。或者我可以将json数组分组为相同的数字,即我的情况下为4。 我是c#的新手,无法找到匹配的代码。 有人可以帮忙吗?感谢。

1 个答案:

答案 0 :(得分:1)

您似乎不希望按键分组,而是按项目数分组。你能尝试一下:

    private string Serialize(List<NameDTO> _nameDetials, List<ValDTO> _valDetials)
    {
        JArray jChildArray = new JArray();
        for (int i = 0; i < Math.Max(_nameDetials.Count, _valDetials.Count) / 4; i++)
        {
            var jChildObject = new JObject();
            for (int j = 0; j < 4; j++)
                jChildObject.Add(_nameDetials[i * 4 + j].Name, _valDetials[i * 4 + j].Val);
            jChildArray.Add(jChildObject);
        }
        return JsonConvert.SerializeObject(jChildArray);
    }