如何写IGrouping的结果?

时间:2017-08-24 18:51:43

标签: c# linq

我编写了以下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.  当我尝试:

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

1 个答案:

答案 0 :(得分: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())
             );
}