LINQ豎錶轉橫表
阿新 • • 發佈:2022-04-11
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using System.Windows.Forms; namespace TISCOMQTT.components { internal class V2H { public static DataTable ConvertDataTable(DataTable source) { try { DataTable dt=new DataTable(); dt.Columns.Add("COIL_NUMBER_IN"); dt.Columns.Add("WORK_TIME"); dt.Columns.Add("DEAL_FLAG"); dt.Columns.Add("PROD_UNIT_CODE"); dt.Columns.Add("PROD_UNIT_SEG"); var columns=(from x in source.Rows.Cast<DataRow>() select x[6].ToString()).Distinct(); foreach(var item in columns) { dt.Columns.Add(item); } var data = from x in source.Rows.Cast<DataRow>() group x by new { subID=x[0], mainID=x[1] } into g select new { key1 = g.Key.subID.ToString(), key2=g.Key.mainID.ToString(),Items = g }; data.ToList().ForEach(x => { String[] array = new string[dt.Columns.Count]; array[0] = x.key1; array[1] = x.key2; for (int i = 2; i < dt.Columns.Count; i++) { array[i] = (from y in x.Items where y[2].ToString() == dt.Columns[i].ToString() select y[4].ToString()+" "+y[5].ToString() ).SingleOrDefault(); } dt.Rows.Add(array); }); return dt; }catch(Exception ex) { MessageBox.Show("豎錶轉橫表錯誤:"+ex.Message.ToString(),"系統提示",MessageBoxButtons.OK,MessageBoxIcon.Error); return null; } } } }