我有一行DataTable,我想将其转换为以下格式:
Column1Name:value
Column2Name:value
Column3Name:value
等...
如何用LINQ完成这个?
谢谢!
答案 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);