&#34;无法将类型&#39; system.linq.igrouping <string,models.cashcall>转换为Models.CashCall&#34;

时间:2015-12-09 14:21:41

标签: linq asp.net-mvc-4 c#-4.0 entity-framework-6

我的代码如下

 public string GetCashCallsbyDate(DateTime _date)
    {
        using (var context = new TildaDbContext())
        {
           List<CashCall> cashcallName = new List<CashCall>();
            try
            {
                CashCall cashCall = new CashCall();
                var cashcalls = context.CashCalls.Where(d => d.Date == _date).GroupBy(g => g.CashCallName).ToList();
                foreach (var data in cashcalls)
                {
                    cashCall = data;   // error here
                    cashcallName.Add(cashCall);
                }
                string CashCallsbyDate = JsonConvert.SerializeObject(cashcallName);
                return CashCallsbyDate;
            }
            catch (Exception e)
            {
                return null;
            }
        }
    }

我的编译时错误为

  

无法将type&type; system.linq.igrouping转换为   Models.CashCall

请帮忙。感谢。

1 个答案:

答案 0 :(得分:0)

这是因为每个循环上的data是一组包含相同名称的一个或多个CashCall个对象。

大概是因为某种原因而对你进行分组,所以通过对每个组中的内容进行循环来取消组合数据(否则GroupBy将完全是多余的)可能是不合适的。所以你可以做一些事情就像获得组中的第一项。例如:

foreach (var data in cashcalls)
{
    cashCall = data.First(); // Gets the first element in the group.
    cashcallName.Add(cashCall);
}

您可能希望聚合组中所有项目的数据,并根据该聚合创建一个新的CashCall对象,但这完全取决于您的使用案例。

如果您确实需要所有cashCall个对象,但只想将所有具有相同名称的对象组合在一起,那么最好使用OrderBy而不是GroupBy