Reputation: 4292
I wrote the following LINQ query:
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.
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>
.
Execution class has the following relevant fields:
public DateTime TimeStamp { get; set; }
public double CashFlow()
{
return Price * Quantity * -1;
}
Upvotes: 0
Views: 98
Reputation: 726639
You are returning an anonymous type rather than 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())
);
}
Upvotes: 1