我有这样的数据和代码用于按国家过滤和计数。但是我只能一个接一个地过滤它们。
数据:
[
{
"Name":"Amal",
"Country":"India",
"salary":"4.000,00"
},
{
"Name":"Luke",
"Country":"England",
"salary":"2.500,00"
},
{
"Name":"Tom",
"Country":"Australia",
"salary":"2.700,00"
},
{
"Name":"Ram",
"Country":"India",
"salary":"2.000,00"
}
]
代码:
using System;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
string inputJson = "[{'Name':'Amal', 'Country':'India','salary':'4.000,00'},{'Name':'Luke', 'Country':'England','salary':'2.500,00'},{'Name':'Tom', 'Country':'Australia','salary':'2.700,00'}, {'Name':'Ram', 'Country':'India','salary':'2.000,00'}]";
var jArrObject = JArray.Parse(inputJson);
Console.WriteLine("***Employee Data***");
var employee = new JArray(jArrObject.SelectTokens("$.[?(@.Country=='India')]"));
Console.WriteLine("Total Employee : "+employee.Count);
Console.WriteLine("Employee : "+employee);
}
}
我希望得到这样的结果:
[
{
"country":"India",
"Total Employee":"2",
"Total Salary":"6.000,00"
},
{
"country":"England",
"Total Employee":"1",
"Total Salary":"2.500,00"
},
{
"country":"Australia",
"Total Employee":"1",
"Total Salary":"2.700,00"
}
]
如何按国家创建数组对象组,并根据国家添加总和?
您可以这样做,将数据投影到匿名类型(或创建要使用的静态类型)。然后,您可以序列化结果或执行任何您想要的操作:
CultureInfo ci = new CultureInfo("en-gb");
ci.NumberFormat.NumberDecimalSeparator= ",";
ci.NumberFormat.NumberGroupSeparator =".";
var result = jArrObject.GroupBy(ao => ao["Country"])
.Select(a => new
{
Country = a.Key,
TotalEmployee = a.Count(),
TotalSalary = a.Sum(x => decimal.Parse(x["salary"].ToString(),NumberStyles.Number, ci ))
});