成績類別:
public class Grade { public string Name { get; set; } public int Value { get; set; } public string Group { get; set; } }
主程式:
List<Grade> val= new List<Grade> { new Grade{Name="alvin",Value=85,Group ="A"}, new Grade{Name="lily",Value=75,Group="B"}, new Grade{Name="john",Value=65,Group="C"}, new Grade{Name="helen",Value=77,Group="B"}, new Grade{Name="mary",Value=78,Group="B"}, new Grade{Name="jack",Value=89,Group="A"}, }; var gok = val.GroupBy(c => c.Group); //GroupBy還沒有將資料取回 var lok = val.ToLookup(c => c.Group); //此段已將資料取回 val.RemoveAll(c => true ); //將原始資料清空 Console.WriteLine("==========GroupBy start=========="); foreach (var g in gok) { Console.WriteLine("=====group:{0}=====", g.Key); foreach (var p in g) { Console.WriteLine("name:{0},value:{1},group:{2}",p.Name ,p.Value ,p.Group ); } } Console.WriteLine("==========ToLookup start=========="); foreach (var g in lok) { Console.WriteLine("=====group-{0}=====", g.Key); foreach (var p in g) { Console.WriteLine("name:{0},value:{1},group:{2}",p.Name ,p.Value ,p.Group ); } } Console.ReadKey();
結果:Groupby沒有資料出現,因為Groupby時沒有立即將資料取回,所以後面Removeall後,再執行就沒資料可用
完整程式碼:
https://www.dropbox.com/s/72p8ayukwaauyun/20141205.txt?dl=0
結果:差別在立即將資料取回(ToLookup)和延遲取回資料(Groupby)
沒有留言:
張貼留言