2017-08-24 60 views
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; 
} 
+3

'選擇新的{}'產生[匿名類型](https://docs.microsoft.com/en-us/ dotnet/csharp/programming-guide/classes-and-structs/anonymous-types) - 它不是* KeyValuePair,所以你不能施放它! –

回答

1

你而返回匿名類型比KeyValuePair<DateTime,double>

可以通過添加適當的類型的方法解決此問題:

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()) 
      ); 
}