2017-08-24 2 views
0

Ich schrieb die folgende LINQ-Abfrage:Wie schreibe ich das Ergebnis von 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; 
} 

ich ein Unbehandelte Ausnahme erhalten: System.InvalidCastException: Specified cast is not valid. , wenn ich versuche zu:

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

Exekutionen ist ein List<Execution>.

Execution Klasse hat die folgenden relevanten Felder:

public DateTime TimeStamp { get; set; } 
public double CashFlow() 
{ 
    return Price * Quantity * -1; 
} 
+3

'wählen neue {}' erzeugt ein [anonymen Typ] (https://docs.microsoft.com/en-us/ dotnet/csharp/programming-guide/classes-and-structs/anonyme-types) - es ist * nicht * ein 'KeyValuePair', also kannst du es nicht casten! –

Antwort

1

Sie einen anonymen Typ Rückkehr statt KeyValuePair<DateTime,double>.

Sie können dieses Problem beheben, indem eine geeignete Art der Methode hinzufügen:

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