2013-07-25 70 views
1

分開後,我有一個數據表,看起來像下面數據表組由逗號

cname tname text  allowgroupping 
A  M  good  Yes 
A  M  bad   Yes 
A  M  ugly  Yes 
B  N  sick  No 
B  N  lovely  No 
C  R  pathatic Yes 

我想組數據表第一列cname所以結果看起來就像

cname tname  text     allowgroupping 
    A  M  good,bad,ugly  Yes 
    B  N  sick,lovely   No 
    C  R  pathatic    Yes 

我通過循環每列並做了大量檢查來完成它,但是我怎樣才能使用LINQ並將結果保存到數據表中?

+1

這SO帖子有你的答案... http://stackoverflow.com/a/7325306/1246574 – Jim

回答

1

你可以做這樣的事情:

var query = from row in dataTable.AsEnumerable() 
       group row by row["cname"] into g 
       select new { cname = g.Key, 
           tname = g.First()["tname"] , 
           text = String.Join(", ", g.Select(r=>r["text"].ToString()).ToArray()), 
           allowgrouping = g.First()["allowgroupping"] 
       }; 

    foreach (var row in query) 
    { 
     resultDataTable.Rows.Add(row.cname, row.tname, row.text, row.allowgrouping); 
    } 
1

的想法是每個組表:

var groupedDB = 
    from entry in dataTable 
    group entry by entry.cName into entryGroup 
    select new 
    { 
    cName = entryGroup.Key, 
    tName = entryGroup.First().tName, 
    text = String.Join(",", entryGroup.Select(_=>_.text)), 
    allowGrouping = entryGroup.First().allowGrouping 
    }; 

當然,一旦你做,你會看到你正在做有關tNameallowGrouping列一些大膽假設。確定你的意思是。如果不是,您應該按照所有三列進行分組,而不僅僅是cName