2017-08-24 5 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. 私がしようとする:死刑執行がList<Execution>ある

foreach (KeyValuePair<DateTime, double> p in s.Executions.DailyReturns()) 
{ 
    Console.WriteLine(p.Key.ToString() + ',' + p.Value.ToString()); 
} 

。あなたはKeyValuePair<DateTime,double>ではなく、匿名型を返すされている

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

実行クラスには、以下の関連フィールドを持っています。

メソッドに適切なタイプを追加することによってこの問題を解決することができ:

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()) 
      ); 
} 
関連する問題