C#将DataTable转换为List <string> </string>

时间:2011-09-19 14:01:10

标签: linq datatable

我有一行DataTable,我想将其转换为以下格式:

Column1Name:value

Column2Name:value

Column3Name:value

等...

如何用LINQ完成这个?

谢谢!

1 个答案:

答案 0 :(得分:3)

如下:

DataTable table = ...

// Overlays the columns over the only row's items
// and combines each column-item pair as required.
var items = table.Columns
                 .Cast<DataColumn>()
                 .Zip(table.AsEnumerable().Single().ItemArray, 
                      (column, value) => column.ColumnName + " : " + value);

var result = string.Join(Environment.NewLine, items);   

这是另一种(IMO更好)方法:

// Uses the DataRow's column-indexer to match a column with 
// the corresponding row-item.
var items = from DataColumn column in table.Columns
            select column.ColumnName  + " : " + table.Rows[0][column];

var result = string.Join(Environment.NewLine, items);