我尝试使用此格式
[
{
name: 'Apple',
data: [
{ name: 'April', y: 35 },
{ name: 'June', y: 1 }
]
},
{
name: 'Orange',
data: [
{ name: 'April', y: 7 },
{ name: 'July', y: 11 },
{ name: 'June', y: 7 },
{ name: 'May', y: 6 }
]
},
{
name: 'Mango',
data: [
{ name: 'July', y: 1 }
]
},
{
name: 'Grapes', data: [
{ name: 'June', y: 1 }
]
},
{
name: 'Cheery',
data: [
{ name: 'June', y: 1 }
]
}
];
所以我尝试使用此代码获取上述格式
var mdata1 = new TrackDataEntities1().spdatasumry(frDate, to_Date, RegNo)
.Select(s => new { s.Name }).ToArray().Distinct();
foreach (var c in mdata1) {
voil.Add(c.Name);
}
var sdata = new TrackDataEntities1().spdatasumry(frDate, to_Date, RegNo)
.Select(s => new {s.Name,s.Month,s.total }).ToArray();
string data2 = "[";
foreach(string vo in voil) {
data2 += "{name:'" + vo + "',";
data2 += "data:[";
foreach(string mo in vmonths) {
decimal tv = 0;
try {
tv = sdata.Single(t => t.Month == mo && t.Name == vo).total;
} catch {
tv = 0;
}
if (tv > 0) {
data2 += "{name:'" + mo + "',y:" + tv + "},";
}
}
data2 += "]},";
}
data2 = data2.Remove(data2.Length - 1);
data2 += "]";
但上面的代码显示格式如下
在下面的代码中,该部分{name:'June',y:1},]},
中有逗号,因此我想删除第二个,]},
逗号以获得正确的格式
"[{name:'Apple',data:[{name:'April',y:35},{name:'June',y:1},]},
{name:'Orange',data:[{name:'April',y:7},{name:'July',y:11},{name:'June',y:7},{name:'May',y:6},]},
{name:'Mango',data:[{name:'July',y:1},]},
{name:'Grapes',data:[{name:'June',y:1},]},
{name:'Cheery',data:[{name:'June',y:1},]}]"
答案 0 :(得分:0)
您在每个节点添加一个额外的逗号是错误的。您将不得不跳过在上一个节点中添加逗号,如下所示:
var i = 0;
foreach(string vo in voil) {
data2 += "{name:'" + vo + "',";
data2 += "data:[";
var j = 0;
foreach(string mo in vmonths) {
decimal tv = 0;
try {
tv = sdata.Single(t => t.Month == mo && t.Name == vo).total;
} catch {
tv = 0;
}
if (tv > 0) {
j++;
if(vmonths.Length == j){
data2 += "{name:'" + mo + "',y:" + tv + "}";
}else{
data2 += "{name:'" + mo + "',y:" + tv + "},";
}
}
}
i++;
if(voil.Length == i){
data2 += "]}";
}else{
data2 += "]},";
}
}