在Linq中创建自定义列,总和为列

时间:2014-11-25 21:02:50

标签: c# linq

如何使用linq创建自定义列?因为我总是得到错误

图。 1

  

序列包含多个元素

我选择作为上下文的网格数据 enter image description here

我的代码在删除iv'e创建TotalAmount

的自定义列时似乎正确
var studentservices = from ser in result.ToList()
                                          where partStudentServices.Contains(ser.Description)
                                          group ser by ser.Description into gser
                                          select new
                                          {
                                              CCode = gser.FirstOrDefault().Code,
                                              CDescription = gser.FirstOrDefault().Description,
                                              CAmount = gser.Where(s => s.EducationLevel == "College").Select(ns => ns.Amount).Sum(),
                                              HAmount = gser.Where(s => s.EducationLevel == "High School").Select(ns => ns.Amount).Sum(),
                                              GAmount = gser.Where(s => s.EducationLevel == "Grade School").Select(ns => ns.Amount).Sum(),
                                              KAmount = gser.Where(s => s.EducationLevel == "Kinder").Select(ns => ns.Amount).Sum(),
                                              TotalAmount = gser.GroupBy(g => g.Description).Select(ns => ns.Sum(sumn => sumn.Amount))
                                          };


                    d.StudentServicesReport.DataSource = studentservices.ToList();
                    d.xTC_StudentServices_Code.DataBindings.Add("Text", null, "CCode");
                    d.xTC_StudentServices_Name.DataBindings.Add("Text", null, "CDescription");
                    d.xTC_StudentServices_College.DataBindings.Add("Text", null, "CAmount");
                    d.xTC_StudentServices_HS.DataBindings.Add("Text", null, "HAmount");
                    d.xTC_StudentServices_GS.DataBindings.Add("Text", null, "GAmount");
                    d.xTC_StudentServices_PS.DataBindings.Add("Text", null, "KAmount");
                    d.xTC_StudentServices_CollegeTotal.Text = studentservices.Select(sa => sa.CAmount).Sum().ToString();
                    d.xTC_StudentServices_HSTotal.Text = studentservices.Select(sa => sa.HAmount).Sum().ToString();
                    d.xTC_StudentServices_GSTotal.Text = studentservices.Select(sa => sa.GAmount).Sum().ToString();
                    d.xTC_StudentServices_PSTotal.Text = studentservices.Select(sa => sa.KAmount).Sum().ToString();
                    d.xTC_StudentServices_Total.Text = studentservices.Select(sa => sa.TotalAmount).ToString();

但是得到错误见图1

因为我要生成一个报告,这应该是输出。红色文本应该是每行的总量。 enter image description here

打印我指定的单元格上显示的错误。 enter image description here

任何人都可以帮助我吗?我被困在这个模块上大约1个小时。

1 个答案:

答案 0 :(得分:2)

不是100%确定,但看起来您的TotalAmount任务可能不正确。您是否尝试过以下方法:

 TotalAmount = gser.Sum(sumn => sumn.Amount)

我相信你拥有它的方式,.Select返回一个IEnumerable,你试图将它作为标签的值分配,所以它只是显示类型。