Reputation: 37
public class NameDTO
{
public string Name;
}
public class ValDTO
{
public string Val;
}
_nameDetials = new List<NameDTO>();
_valDetials = new List<ValDTO>();
Into List _nameDetials I get keys and into _valDetails I get values for which I used below for block and added them to array. In my given values below i get count as 20 into each of the lists.
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);
}
I have a json array as shown below
[
{
"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"
}
]
I want to group this data to get the result as shown below.
[
{
"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"
}
]
I want to group based on same key names.
I tried the below code
var grouparray = (from t in jChildArray
group t by new { t }
into grp
select grp.Key.t).ToList();
I am unable to trace what is that I am missing.Or can we group a json array into equal number i.e. 4 in my case. I am new to c# and unable to find a matching code. Can anyone help? Thanks.
Upvotes: 1
Views: 623
Reputation: 3161
It seems that you do not want to group by the key but rather by number of items. Can you try:
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);
}
Upvotes: 1