如何使用实体框架将相似的记录分组到GridView中的Linq

如何使用实体框架将相似的记录分组到GridView中的Linq

本文介绍了如何使用实体框架将相似的记录分组到GridView中的Linq的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Name             score   address
John            100       Ph
grace          200        AB
john           50         PH
grace          100        AB

//I have this records in my database and i want to group similar records and preview it in a gridview... I have been trying to do that and i have been getting error

to populate the above in a gridview using LINQ to Entity Framework i use this and it is working fine
       var try = (from c in schoolEnt.scores
                      where
                  c.name != null

                      select c).ToList();
//this gives me all the values now i want to group them
i tried using
  var try = (from c in schoolEnt.scores
                      where
                  c.name != null
                     group c by c.name into ord
                      select ord.orderBy{g=new{ScoreId = ord.Key, Address = g.Address,  Name = g.name, Score =ord.sum(x=>x.score) ).ToList();
gridview1.datasource = try,
gridview1.databind();
//I get error when i run this code,
my Intention is to have them show like this in a grid view
Name                     score
John            150
grace          300

//thats all..i do appreciate your time and help... thanks very much

推荐答案

gridview1.datasource =schoolEnt.scores.Where(s=> s.name !=null)
         .GroupBy(c=>c.name)
         .Select(g=> new{Name =g.Key, Score =g.Sum(x=>x.score)})
         .ToList();





如果你还需要获得地址





If you need to get Address as well

gridview1.datasource =schoolEnt.scores.Where(s=> s.name !=null)
         .GroupBy(c=>c.name)
         .Select(g=> new{Name =g.Key, Score =g.Sum(x=>x.score), Address =g.Select(f => f.Address).FirstOrDefault()})
         .ToList();


var try = from c in schoolEnt.scores.Where(s=> s.name !=null)
         .GroupBy(c=>c.name)
         select new {Name =c.Key, Score =c.Sum(x=>x.score), Address =c.Select(f => f.Address)}.
         .ToList();
/*I had to modify the code to that above and it worked fine for me... i am able to get what i am looking for..thank you.. i do appreciate.... however, i am thinking of geting the minimum value and the maximum value.. and populate the values to the gridview....
*/


这篇关于如何使用实体框架将相似的记录分组到GridView中的Linq的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-15 08:39