日期:2014-05-20  浏览次数:20907 次

LINQ不能返回新的数据类型吗?如需要重新组合数据怎么办?
先贴代码比较好理解
C# code

var linqValue = from item in db.consume
                                group item by new
                                {
                                    item.je_createdate.Value.Year,
                                    item.je_createdate.Value.Month
                                } into g
                                select new
                                {
                                    monthday = String.Format("{0}年-{1}月",g.Key.Year,g.Key.Month),
                                    totalmoney = g.Sum(d => d.je_amount)
                                };

                dataGridView3.DataSource = linqValue;


上面段是错误的,错在
"monthday = String.Format("{0}年{1}月",g.Key.Year,g.Key.Month),"我是想返回"2011年-7月"这样的数据格式。但提示:
LINQ to Entities 不识别方法"System.String.Format(...",因此该方法无法转换为存储表达式



------解决方案--------------------
HEY,Try This:

C# code

var linqValue =( from item in db.consume
                                group item by new
                                {
                                    item.je_createdate.Value.Year,
                                    item.je_createdate.Value.Month
                                } into g
                                select new
                                {
                    Year=g.Key.Year,
                    Month=g.Key.Month,
                                    totalmoney = g.Sum(d => d.je_amount)
                                }).ToList().Select(t=>new{
                                   monthday = String.Format("{0}年-{1}月",t.Year,t.Month),
                                   totalmoney =t.totalmoney 
                                 };

                dataGridView3.DataSource = linqValue;