Jawad Rauf Jawad Rauf - 3 months ago 13
C# Question

How to seperate comma seperated values in List Array as a single Datarow

My List array List lines = new List(); contains below data:

MSC,1
MSC,2
MSC,3


Now i want to use column 1 as Xaxis and column 2 as Yaxis in chart. Below is my code i did try but its not working properly. Please help me correct this code.

DataSet dataSet = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Counter", typeof(string));
foreach (string str in lines)
{
DataRow r1 = dt.NewRow();
r1[0] = str; // Assign values
dt.Rows.Add(r1);
DataRow r2 = dt.NewRow();
r1[1] = str; // Assign values
dt.Rows.Add(r2);

}


My output is given below. I want these 1,2,3 and 4 values on y-axis.

enter image description here

Answer

You could use the string.Split method for each line split the content by ,. After that, use any item and define a new row on the DataTable. For sample:

DataSet dataSet = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Counter", typeof(string));
foreach (string line in lines)
{
    var values = line.Split(new[] { ',' });
    DataRow row = dt.NewRow();  
    row["Name"] = values[0];
    row["Counter"] = values[1];
    dt.Rows.Add(row);
}