LINQ 中的关于group by的问题
问题描述:就是从数据库中取出数据,经过group bu之后分组显示
两种方法:
1:建立一个实体数据模型,直接从映射之后的实体类中分组显示(发现了问题)
using (studentEntities entities =new studentEntities()) { var item1 = (from c in entities.Score group c by c.ID into g select new { g.Key, g }); foreach (var m in item1) { if (m.Key == "11112") { foreach (var n in m.g) Console.WriteLine(n.ID + " " + n.course + " " + n.score1); } }class Program { static void Main(string[] args) { using (studentEntities entities = new studentEntities()) { var v = from u in GetScore() group u by u.Num into g select new { Sss = g.Key, Mdd = g }; foreach (var m in v) { foreach(var n in m.Mdd) Console.WriteLine(n.Num + " " + n.Name + " " + n.Fen); } Console.ReadLine(); } } public static List<ScoreS> GetScore() { List<ScoreS> mylist = null; using (studentEntities entities = new studentEntities()) { var v = from u in entities.Score select new ScoreS { Num = u.ID, Name = u.course, Fen = u.score1 }; mylist = v.ToList(); } return mylist; } }
LINQ语句看着也没问题,再想想。
[解决办法]
try..
var item1 = (from c in entities.Score group c by c.ID select g) .ToDictionary(g => g.Key); foreach (var pk in item1){ if (pk.Key == "11112") { foreach (var n in pk.Value) Console.WriteLine(n.ID + " " + n.course + " " + n.score1); } }
[解决办法]
(g => g.ID)
[解决办法]
using (NorthwindEntities entities = new NorthwindEntities()){ var groupedResult = entities.Customers .GroupBy(c => c.City) .Select(g => new { g.Key, g }); foreach (var e in groupedResult) { if (e.Key=="London") foreach (var c in e.g) { Console.WriteLine("{0} {1} {2} {3}", c.CustomerID, c.City, c.ContactName, c.Country); } }}