Linq 实现行转列(作者caozhy)

static DataTable ConvertDataTable(DataTable source)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("id");
            var columns = (from x in source.Rows.Cast() select x[1].ToString()).Distinct();
            foreach (var item in columns) dt.Columns.Add(item);
            var data = from x in source.Rows.Cast()
                       group x by x[0] into g
                       select new { Key = g.Key.ToString(), Items = g };
            data.ToList().ForEach(x => 
                {
                    string[] array = new string[dt.Columns.Count];
                    array[0] = x.Key;
                    for (int i = 1; i < dt.Columns.Count; i++)
                        array[i] = (from y in x.Items
                                    where y[1].ToString() == dt.Columns[i].ToString()
                                    select y[2].ToString())
                                   .SingleOrDefault();
                    dt.Rows.Add(array);
                });
            return dt;
        }


你可能感兴趣的:(Linq 实现行转列(作者caozhy))