1

I have a 1 row DataTable that I'd like to convert to the following format:

Column1Name : value

Column2Name : value

Column3Name : value

etc...

How can this be accomplished with LINQ??

Thanks!

0

1 Answer 1

3

How about something like:

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);   

Here's another (IMO better) approach:

// 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); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I have tweaked it so it can work for any number of rows. 'var xxx = from DataRow row in table.Rows from DataColumn column in row.Table.Columns select column.ColumnName + " : " + row[column];'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.