1. 程式人生 > >用linq對datatable分組查詢並返回datatable

用linq對datatable分組查詢並返回datatable

DataTable dataTable = new DataTable();
                dataTable.Columns.Add("FDATE");
                dataTable.Columns.Add("FHOUR");
                dataTable.Columns.Add("FALARMCODE");
                dataTable.Columns.Add("FTIMES");
                dataTable.Columns.Add("FEQUNO");
                var query = from dt in datatable1.AsEnumerable()
                            group dt by new
                            {
                                AlarmDate = dt.Field<string>("AlarmDate"),
                                AlarmHour = dt.Field<string>("AlarmHour"),
                                AlarmCode = dt.Field<string>("AlarmCode"),
                                EquNo = dt.Field<string>("EquNo")
                            }
                                into g
                                select new
                                    {
                                        g.Key.AlarmDate,
                                        g.Key.AlarmHour,
                                        g.Key.AlarmCode,
                                        Times = g.Count(),
                                        g.Key.EquNo
                                    };
                foreach (var item in query)
                {
                    DataRow dr = dataTable.NewRow();
                    dr["FDATE"] = item.AlarmDate;
                    dr["FHOUR"] = item.AlarmHour;
                    dr["FALARMCODE"] = item.AlarmCode;
                    dr["FTIMES"] = item.Times;
                    dr["FEQUNO"] = item.EquNo;
                    dataTable.Rows.Add(dr);
                }