Test Code/C#
[Linq] DataTable에서 Linq 사용하기 Group By
yaks101
2015. 3. 4. 16:09
using System; using System.Linq; using System.Data; class Test_Linq { static void Main() { DataTable table = new DataTable(); table.Columns.Add("lot"); table.Columns.Add("data",typeof(double)); table.Rows.Add("A", 45.2); table.Rows.Add("A", 45.8); table.Rows.Add("A", 45.9); table.Rows.Add("B", 45.1); table.Rows.Add("B", 45.5); table.AcceptChanges(); // Group By var query = from dr in table.AsEnumerable() group dr by dr["lot"] into gg select new { lot = gg.Key, count = gg.Count(), min = gg.Min(r=>r.Field<double>("data")), max = gg.Max(r=>r.Field<double>("data")), mean = Math.Round(gg.Average(r=>r.Field<double>("data")), 4), sum = gg.Sum(r=>r.Field<double>("data")), qsm = gg.Sum(r=>Math.Pow(r.Field<double>("data"), 2)) }; // Display double stdDev = 0; Console.WriteLine("**. Select 결과"); Console.WriteLine("Lot\t개수\t최대값\t최소값\t평균\t합계\t제곱합\t표준편차"); foreach(var x in query) { stdDev = Math.Sqrt((x.qsm-x.count*(x.mean*x.mean))/(x.count-1)); stdDev = Math.Round(stdDev, 4); Console.WriteLine( "{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}", x.lot, x.count, x.max, x.min, x.mean, x.sum, x.qsm, stdDev ); } } }