簡體   English   中英

如何編寫IGrouping的結果?

[英]How to write the result of IGrouping?

我編寫了以下LINQ查詢:

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.的強制轉換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;
}

您將返回匿名類型,而不是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())
             );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM