将数据表分组并复制到另一个表C#

时间:2014-11-25 15:21:57

标签: c# linq datatable

这里已经存在一个问题" https://stackoverflow.com/questions/27121248/report-generation-in-asp-net"。我有同样的情况,我已经存储了一个特定的点。

请帮助。

我的DataTable有三列

Name  Plot   Area
a     12     .90
a     13     .30
b     12     .45
b     13     .46
c     13     .98

我希望我的结果是

Name  Plot  Area
a     12    .90
      13    .30
b     12    .45
      13    .46
c     13    .98

这就是我的尝试。我已将其分组为linq并需要复制到另一个表。我怎样才能做到这一点:

static class Program
{
    static void Main(string[] args)
    {
        try
        {

            DataTable dtMain = new DataTable();
            dtMain.Columns.Add("Name", typeof(string));
            dtMain.Columns.Add("Plot", typeof(int));
            dtMain.Columns.Add("Area", typeof(decimal));

            DataRow dr1 = dtMain.NewRow();
            dr1["Name"] = "a";
            dr1["Plot"] = 12;
            dr1["Area"] = .90;
            dtMain.Rows.Add(dr1);

            DataRow dr2 = dtMain.NewRow();
            dr2["Name"] = "a";
            dr2["Plot"] = 13;
            dr2["Area"] = .30;
            dtMain.Rows.Add(dr2);

            DataRow dr3 = dtMain.NewRow();
            dr3["Name"] = "b";
            dr3["Plot"] = 12;
            dr3["Area"] = .45;
            dtMain.Rows.Add(dr3);
            DataRow dr4 = dtMain.NewRow();
            dr4["Name"] = "b";
            dr4["Plot"] = 13;
            dr4["Area"] = .46;
            dtMain.Rows.Add(dr4);
            DataRow dr5 = dtMain.NewRow();
            dr5["Name"] = "c";
            dr5["Plot"] = 13;
            dr5["Area"] = .98;
            dtMain.Rows.Add(dr5);

            DataTable dtFinal = dtMain.Clone();

            var groupedData = (from b in dtMain.AsEnumerable()
                               group b by b.Field<string>("Name") into g
                               select new
                              {
                                  Name = g.Key,
                                  Plot = g.Select(x => x.Field<int>("Plot")),
                                  Area = g.Select(x => x.Field<Decimal>("Area")),
                              }).ToList();

      //Next what should i do here.CopyToDataTable() no longer getting the correct data.
       dtFinal = groupedData.ToList().CopyToDataTable();

            Console.ReadLine();
        }
        catch (Exception objEx)
        {
            Console.WriteLine(objEx);
        }
    }


}

3 个答案:

答案 0 :(得分:0)

如果你想要做的只是让Name出现一次,你需要更改你的查询:

dtMain.AsEnumerable()
  .GroupBy(b => b.Field<string>("Name"))
  .SelectMany(g => g.Select((x,idx) => new
                            {
                                Name = idx == 0 ? g.Key : "",
                                Plot = x.Field<int>("Plot"),
                                Area = x.Field<Decimal>("Area"),
                            }).ToList();

答案 1 :(得分:0)

int index = 0;
bool saveIndex = false;

DataTable table = sourceTable.Copy();

for(int i=0; i< table.Rows.Count; i++)
{
    if(i==0)
      continue;

    if(!saveIndex)
       index = i-1;

   if(table.Rows[i]["Name"] == table.Rows[index]["Name"])
   {
        table.Rows[i]["Name"] = "";

        saveIndex = true;
   }
   else
   {
       saveIndex = false;
   }

}

我不知道你的领域的限制,但这可能会有所帮助。

我在你之前的回答中给你写了这个,希望它有所帮助!

答案 2 :(得分:-1)

不要害怕使用循环;)

var nameGroups = dtMain.AsEnumerable().GroupBy(row => row.Field<string>("Name"));

foreach (var nameGroup in nameGroups)
{
    bool isFirstRow = true;
    foreach (DataRow row in nameGroup)
    {
        DataRow newRow = dtFinal.Rows.Add();
        newRow.SetField("Name", isFirstRow ? nameGroup.Key : "");
        newRow.SetField("Plot", row.Field<int>("Plot"));
        newRow.SetField("Area", row.Field<decimal>("Area"));
        isFirstRow = false;
    }              
}

LINQ不应该引起副作用。因此,使用它来选择创建表格所需的内容。

结果:

a      12     0.9
       13     0.3
b      12     0.45
       13     0.46
c      13     0.98

如果你坚持避免循环,这就是你应该使用它们的原因。看看这个丑陋,低效和奇怪的问题:

DataTable dtFinal = dtMain.Clone();
dtFinal = dtMain.AsEnumerable()
    .GroupBy(row => row.Field<string>("Name"))
    .SelectMany(grp => grp.Select((row, index)=> index == 0
        ? dtFinal.LoadDataRow(new object[]{ grp.Key, row.Field<int>("Plot"), row.Field<decimal>("Area")}, true)
        : dtFinal.LoadDataRow(new object[]{ "", row.Field<int>("Plot"), row.Field<decimal>("Area")}, true)))
    .CopyToDataTable();