按LINQ平均值分组
本文关键字:平均值 LINQ | 更新日期: 2023-09-27 17:49:32
在文件普查。我有以下数据:
[
{
"savingsBalance": "$16,264.00",
"age": 38,
"firstname": "Carmella",
"lastname": "Mcguire",
"gender": "female",
"company": "Vicon",
"email": "carmellamcguire@vicon.com",
"phone": "+1 (877) 400-3279",
"city": "Fresno",
"state": "Minnesota"
},
{
"savingsBalance": "$10,228.00",
"age": 30,
"firstname": "Ollie",
"lastname": "Wolfe",
"gender": "female",
"company": "Kengen",
"email": "olliewolfe@kengen.com",
"phone": "+1 (934) 564-2156",
"city": "Felt",
"state": "Tennessee"
}
]
当然,在file中,它们的数目要多得多。我想把它按savingsBalance分类。我在做什么:
首先从文件中加载数据:
var jsonStringCensus = File.ReadAllText("C:''...''Census.json");
然后我要反序列化它:
var censuses = JsonConvert.DeserializeObject<IEnumerable<Census>>(jsonStringCensus);
我可以把它打印到控制台:
var data = censuses.Select(x => string.Format("{0} {1}" ,x.state, x.savingsBalance.Substring(1)));
var dataPrintable = averageSavingBalancePerState.Select(x => string.Format("{0} {1}", x.Key));
Console.WriteLine(dataPrintable);
最后,我想按州分组并打印平均储蓄余额:
var dataDouble =
from w in censuses
group w by w.state into g
select new { GState = g.Key, Average = g.Average(p => { double a; a = Convert.ToDouble(p.savingsBalance); return a; }) };
foreach (var g in dataDouble)
{
Console.WriteLine("The state '{0}':", g.GState);
foreach (var w in g.Average.ToString())
{
Console.WriteLine(w);
}
}
我没有任何错误,它是编译。但是当程序执行时,我有异常:
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
Additional information: Input string was not in a correct format. The exception appear before line
select new { GState = g.Key, Average = g.Average(p => { double a; a = Convert.ToDouble(p.savingsBalance); return a; }) };
你知道我为什么要做才能得到正确的结果吗?提前感谢
使用Double.Parse
(或Timothy建议的Decimal.Parse
)从货币样式的字符串中解析double:
from c in censuses
group c by c.state into g
select new {
GState = g.Key,
Average = g.Average(c => Double.Parse(c.savingsBalance, NumberStyles.Currency))
}