larryq
larryq

Reputation: 16309

IGrouping does not contain a definition for Sum

Would anyone have an idea what's up here? I'm loading an XML file, parsing it and using LINQ to get some summary info. Here's the XML document:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <Ticker>
    <Name>MSFT</Name>
    <PurchaseDate>
      2009-01-01
    </PurchaseDate>
    <Shares>44</Shares>
  </Ticker>
  <Ticker>
    <Name>MSFT</Name>
    <PurchaseDate>
      2009-03-01
    </PurchaseDate>
    <Shares>33</Shares>
  </Ticker>
  <Ticker>
    <Name>GOOG</Name>
    <PurchaseDate>
      2009-03-01
    </PurchaseDate>
    <Shares>122</Shares>
  </Ticker>
  <Ticker>
    <Name>AAPL</Name>
    <PurchaseDate>
      2019-03-01
    </PurchaseDate>
    <Shares>89</Shares>
  </Ticker>
</root>

My code:

var xmlStr = File.ReadAllText("ClientInfo.xml");
var Summary = XElement.Parse(xmlStr);
var data = from acct in Summary.Elements("Ticker")
       select new
       {
           Ticker = (string)acct.Element("Name"),
           Shares = (int)acct.Element("Shares")
       };

var groupedDataByTicker = from acct in data
                          group acct by acct.Ticker into g
                          select new
                          {
                              Ticker = g.Key,
                              Shares = g.Sum(),
                          };

Works fine but when I add the g.Sum() bit I get this message:

'IGrouping>' does not contain a definition for 'Sum' and the best extension method overload 'Queryable.Sum(IQueryable)' requires a receiver of type 'IQueryable'

I can't make sense of it, what am I doing wrong?

Upvotes: 0

Views: 466

Answers (1)

Kei
Kei

Reputation: 1026

In your code, you are trying to find the sum of the group itself.

Instead, you should be summing by the Shares property:

var groupedDataByTicker = from acct in data
                          group acct by acct.Ticker into g
                          select new
                          {
                              Ticker = g.Key,
                              Shares = g.Sum(row => row.Shares),
                          };

Upvotes: 1

Related Questions