EDIT: I'm giving the credit to Nick as his answer pointed me in the right direction. In his answer he had set all DataColumns to be retrieved as String, but not all columns in the DataTable were strings. Also Select() was appropriate to get individual rows whereas SelectMany() joined all column values for multiple rows into a single array, or one big row if you will. Here is the solution:
using (dataTable)
using (var sw = new StreamWriter(resultPath, false))
{
DataColumn[]
exclCols = { dataTable.Columns["registryvalue"] }, //excluded
inclCols = dataTable.Columns //included columns
.Cast<DataColumn>()
.Except(exclCols)
.ToArray();
sw.WriteLine(String.Join( //header line
",", inclCols.Select(column => column.ColumnName).ToArray()));
foreach (var row in dataTable.AsEnumerable().Select(
dataRow => inclCols.Select(column => dataRow.Field<Object>(column))))
{
sw.WriteLine(String.Join(
",", row.Select(r => (r == null) ?
"" : r.ToString()).ToArray()));
}
}
I'm using foreach to loop through the rows of a DataTable. There are only certain columns' values that I want from the DataRow and I want to convert this subset of values into a string array (we'll call it myStringArray). The end result is:
StreamWriter.WriteLine(String.Join(",", myStringArray))
I can accomplish writing the line without using LINQ, but then that doesn't help me better understand LINQ. Getting the subset of column names I want into an array is easy, but I just don't know how to use that array to get only those columns' data from the DataRow.
DataTable
. Maybe you should clarify this in your question. – Orkun Ozen