Jacob
Jacob

Reputation: 829

Group by with average in LINQ

In file Census.json I have data as below:

[
    {
        "savingsBalance": "$16,264.00",
        "age": 38,
        "firstname": "Carmella",
        "lastname": "Mcguire",
        "gender": "female",
        "company": "Vicon",
        "email": "[email protected]",
        "phone": "+1 (877) 400-3279",
        "city": "Fresno",
        "state": "Minnesota"
    },
    {
        "savingsBalance": "$10,228.00",
        "age": 30,
        "firstname": "Ollie",
        "lastname": "Wolfe",
        "gender": "female",
        "company": "Kengen",
        "email": "[email protected]",
        "phone": "+1 (934) 564-2156",
        "city": "Felt",
        "state": "Tennessee"
    }
]

Of course, in file, there is much more of them. I would like group it by savingsBalance. What I am doing:

firstly I load data from file:

var jsonStringCensus = File.ReadAllText("C:\\...\\Census.json");

Then I have to deserialize it:

var censuses = JsonConvert.DeserializeObject<IEnumerable<Census>>(jsonStringCensus);

I can print it into console:

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);

And finally, I would like group it by state and print average savingsBalances:

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);
        }
    }

I don't have any errors and it is compiles.But when programm is executed I have exception:

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; }) };

Do you have any idea why should I do to get correct result? Thanks in advance

Upvotes: 2

Views: 1448

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

Use Double.Parse (or Decimal.Parse as Timothy suggests) to parse double from string in currency style:

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

Upvotes: 4

Related Questions