在LINQ中按平均分组

时间:2014-03-10 16:55:18

标签: c# linq

在Census.json文件中,我的数据如下:

[
    {
        "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"
    }
]

当然,在档案中,还有更多。 我想通过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; }) };

你知道我为什么要做正确的结果吗?提前致谢

1 个答案:

答案 0 :(得分:4)

使用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))
}