在我的asp.net Web API中,JSON字符串返回如下。
[
{
"Company": "Company A",
"ProjectName": "Project A",
"Developer": "No developer assigned",
"Hour": 0,
"Overtime": 0,
"Contribution": "0"
},
{
"Company": "Company A",
"ProjectName": "Project B",
"Developer": "paul",
"Hour": 36,
"Overtime": 27,
"Contribution": "71.5909%"
},
{
"Company": "Company A",
"ProjectName": "Project B",
"Developer": "kalpa",
"Hour": 16,
"Overtime": 9,
"Contribution": "28.4091%"
},
{
"Company": "Company B",
"ProjectName": "Project C",
"Developer": "shane",
"Hour": 40,
"Overtime": 14,
"Contribution": "78.2609%"
},
{
"Company": "Company B",
"ProjectName": "Project C",
"Developer": "kal",
"Hour": 10,
"Overtime": 5,
"Contribution": "21.7391%"
},
{
"Company": "Company C",
"ProjectName": "Project D",
"Developer": "No developer assigned",
"Hour": 0,
"Overtime": 0,
"Contribution": "0"
},
{
"Company": "Company D",
"ProjectName": "Project E",
"Developer": "No developer assigned",
"Hour": 0,
"Overtime": 0,
"Contribution": "0"
}
]
当我在我的C#桌面应用程序上使用我的API并将该JSON字符串显示为以下图像时:
这是我的C#桌面应用程序代码,用于在datagridview
方法中显示setGrid
中的JSON对象,该方法将JSON对象作为参数显示在datgridview
上。
public void setGrid(string obj)
{
try
{
var json = JsonConvert.DeserializeObject<dynamic>(obj);
dataGridView1.DataSource = json;
}
catch (Exception)
{
throw;
}
}
但我需要将此结果显示为以下图像。我需要将公司列合并为相同的值。此图像显示预期结果:
我该怎么做?
答案 0 :(得分:0)
因此,在看到图像之后,任务似乎需要System.Linq
。您首先需要对数据进行分组。
我创建了一个方法,为我提供了你提到的JSON
。
public static IEnumerable<ProjectInfo> GetResponse()
{
IEnumerable<ProjectInfo> items = new List<ProjectInfo>();
using (StreamReader r = new StreamReader("Data.json"))
{
string json = r.ReadToEnd();
items = JsonConvert.DeserializeObject<List<ProjectInfo>>(json);
}
return items;
}
ProjectInfo
类的定义如下:
public class ProjectInfo
{
public string Company { get; set; }
public string ProjectName { get; set; }
public string Developer { get; set; }
public int Hour { get; set; }
public int Overtime { get; set; }
public string Contribution { get; set; }
}
现在转到代码,使用System.Linq
对list
属性<{1}}进行分组
Company
现在你有一个分组的集合。使用以下模板作为var APIResponse = GetResponse();
var grouped = APIResponse.GroupBy(x => x.Company);
GridView
来源: