简体   繁体   中英

How to write the result of IGrouping?

I wrote the following LINQ query:

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

I get a Unhandled Exception: System.InvalidCastException: Specified cast is not valid. when I try to:

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

Executions is a List<Execution> .

Execution class has the following relevant fields:

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

You are returning an anonymous type rather than KeyValuePair<DateTime,double> .

You can fix this by adding an appropriate type to the method:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM