Reputation: 5830
i have C# DataTable
in format as below
Name Value1 Value2 Value3
A 5 5 0
B 6 3 1
C 4 9 9
Expected format in string should be as
string sDataTableOutput = "A,B,C|Value1,5,6,4|Value2,5,3,9|Value3,0,1,9";
I want Column Header with data (except for first column)
i try hard to write below code but couldnt get it done
DataTable dtGraphOutput[0] = //Get DataTable Data ;
foreach (DataColumn dcOutput in dtGraphOutput[0].Columns)
{
foreach (DataRow drOutput in dtGraphOutput[0].Rows)
{
sTicketTypeCount += ((sTicketTypeCount == "") ? "" : ",") + dcOutput.ColumnName + Convert.ToString(drOutput[dcOutput]);
}
sTicketTypeCount += ((sTicketTypeCount == "") ? "" : "|");
}
Its giving me output as
NameA,NameB,NameC|,Value15,Value16,Value14|,Value25,Value23,Value29|,Value30,Value31,Value39|
Upvotes: 0
Views: 3542
Reputation: 460340
This is LINQ and gives you the desired result:
var rows = dt.AsEnumerable();
var firstCol = string.Join(",", rows.Select(r => r.Field<string>(0)));
var otherColumns = dt.Columns.Cast<DataColumn>().Skip(1)
.Select(dc => string.Format("{0},{1}",
dc.ColumnName,
string.Join(",", rows.Select(r => r.Field<int>(dc)))));
string sDataTableOutput = string.Format("{0}|{1}",
firstCol,
string.Join("|", otherColumns));
Result: A,B,C|Value1,5,6,4|Value2,5,3,9|Value3,0,1,9
Upvotes: 1
Reputation: 63387
string sDataTableOutput = string.Join("|",
dtGraphOutput[0].Columns
.OfType<DataColumn>()
.Select((c,i) =>
string.Join(",",
dtGraphOutput[0].Rows
.OfType<DataRow>()
.Select((r,j)=>
(j == 0 && i != 0 ? c.ColumnName + "," : "") + r[c.ColumnName])
.ToArray())).ToArray());
.
Upvotes: 1
Reputation: 1121
Try this:
DataTable dtGraphOutput[0] = //Get DataTable Data ;
foreach (DataColumn dcOutput in dtGraphOutput[0].Columns)
{
sTicketTypeCount +=dcOutput.ColumnName
foreach (DataRow drOutput in dtGraphOutput[0].Rows)
{
sTicketTypeCount += ","+ dcOutput.ColumnName + Convert.ToString(drOutput[dcOutput]);
}
sTicketTypeCount += ((sTicketTypeCount == "") ? "" : "|");
}
if you have problem with the last "|" you can remove it with a simple if
Upvotes: 0