[英]How to write the result of IGrouping?
I wrote the following LINQ query: 我编写了以下LINQ查询:
public IEnumerable DailyReturns()
{
var a = from exec in executions
group exec by exec.TimeStamp.Date into execGroup
select new { TimeStamp = execGroup.Key, CashFlow = execGroup.Sum(e => e.CashFlow())};
return a;
}
I get a Unhandled Exception: System.InvalidCastException: Specified cast is not valid.
我收到未处理的异常:
System.InvalidCastException: Specified cast is not valid.
的强制转换System.InvalidCastException: Specified cast is not valid.
when I try to: 当我尝试:
foreach (KeyValuePair<DateTime, double> p in s.Executions.DailyReturns())
{
Console.WriteLine(p.Key.ToString() + ',' + p.Value.ToString());
}
Executions is a List<Execution>
. 执行是一个
List<Execution>
。
Execution class has the following relevant fields: 执行类具有以下相关字段:
public DateTime TimeStamp { get; set; }
public double CashFlow()
{
return Price * Quantity * -1;
}
You are returning an anonymous type rather than KeyValuePair<DateTime,double>
. 您将返回匿名类型,而不是
KeyValuePair<DateTime,double>
。
You can fix this by adding an appropriate type to the method: 您可以通过在方法中添加适当的类型来解决此问题:
public IEnumerable<KeyValuePair<DateTime,double>> DailyReturns() {
return from exec in executions
group exec by exec.TimeStamp.Date into execGroup
select new KeyValuePair<DateTime,double>(
execGroup.Key
, execGroup.Sum(e => e.CashFlow())
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.