有人会知道这里发生了什么吗?我正在加载XML文件,对其进行解析并使用LINQ获取一些摘要信息。这是XML文档:
<?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>
我的代码:
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(),
};
工作正常,但是当我添加g.Sum()
位时,我收到此消息:
'IGrouping>'不包含'Sum'的定义,最佳扩展方法重载'Queryable.Sum(IQueryable)'需要类型为'IQueryable'的接收器
我无法理解,我做错了什么?
答案 0 :(得分:1)
在您的代码中,您试图找到组本身的总和。
相反,您应该通过Shares属性进行求和:
var groupedDataByTicker = from acct in data
group acct by acct.Ticker into g
select new
{
Ticker = g.Key,
Shares = g.Sum(row => row.Shares),
};