【问题标题】:foreach using split in C# and return Json resultforeach 在 C# 中使用 split 并返回 Json 结果
【发布时间】:2020-08-28 23:15:14
【问题描述】:

在我的控制器中

var data1 = data.Split(','); 
List opsi = new List(); 
foreach (string da1 in data1) 
{ 
    string[] data2 = da1.Split(':'); 
    opsi.Add(data2[0]); 
} 

return Json(new 
{ 
    info = form["jml_soal"].ToString(), 
    data = opsi 
}); 

实际结果1,2,3,4,5
预期结果B,C,D,A,D

请帮忙!

【问题讨论】:

  • 您能否提供一个最小的可重现示例,stackoverflow.com/help/minimal-reproducible-example
  • 是的,到目前为止,这看起来很有效,如果 data 是例如“[1:B,2:C,3:D,4:A,5:D]”,你可能想要将data2[0] 更改为data2[1],如果不是,请至少告诉我们您的输入data 实际上是什么

标签: c# asp.net arrays json asp.net-mvc


【解决方案1】:

您只需要将 opsi.Add(data2[0]) 更改为 opsi.Add(data2[1])

注意第一个和最后一个字符

string data = "[1:B,2:C,3:D,4:A,5:D]";

List<string> opsi = new List<string>();

//adding a substring to remove the first and last character [ and ]
var data1 = data.Substring(1, data.Length -2).Split(',');

foreach (string da1 in data1)
{
     string[] data2 = da1.Split(':');
     opsi.Add(data2[1]);
     Console.WriteLine(data2[1]);
}

return Json(new
{
     info = form["jml_soal"].ToString(),
     data = opsi
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-10
    • 2017-11-06
    • 1970-01-01
    • 2011-01-12
    相关资源
    最近更新 更多