0
我寫了下面的LINQ查詢:如何編寫IGrouping的結果?
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;
}
我得到一個未處理的異常:System.InvalidCastException: Specified cast is not valid.
當我嘗試:
foreach (KeyValuePair<DateTime, double> p in s.Executions.DailyReturns())
{
Console.WriteLine(p.Key.ToString() + ',' + p.Value.ToString());
}
處決是List<Execution>
。
執行類具有如下相關字段:
public DateTime TimeStamp { get; set; }
public double CashFlow()
{
return Price * Quantity * -1;
}
'選擇新的{}'產生[匿名類型](https://docs.microsoft.com/en-us/ dotnet/csharp/programming-guide/classes-and-structs/anonymous-types) - 它不是* KeyValuePair,所以你不能施放它! –