CSV string to DataTable

12,663

I don't know if that what are you looking for :

string s = "Id,Name ,Dept\r\n1,Mike,IT\r\n2,Joe,HR\r\n3,Peter,IT\r\n";
        DataTable dt = new DataTable();

        string[] tableData = s.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        var col = from cl in tableData[0].Split(",".ToCharArray())
                  select new DataColumn(cl);
        dt.Columns.AddRange(col.ToArray());

        (from st in tableData.Skip(1)
         select dt.Rows.Add(st.Split(",".ToCharArray()))).ToList();
Share:
12,663
meetjaydeep
Author by

meetjaydeep

Explore

Updated on June 07, 2022

Comments

  • meetjaydeep
    meetjaydeep almost 2 years

    I have following string, I want to convert it to DataTable

    "Id,Name ,Dept\r\n1,Mike,IT\r\n2,Joe,HR\r\n3,Peter,IT\r\n"
    

    I can create it using String.Split and iterating through collection. But I need efficient way (using C# 4.0 features) How to create table using LINQ or lambda.

  • meetjaydeep
    meetjaydeep about 13 years
    dt.Rows.Add( from st in tableData.Skip(1) select st.Split(",".ToCharArray())); its not working it should be foreach (var item in tableData.Skip(1)) { dt.Rows.Add(item.Split(",".ToCharArray())); }
  • AlaaL
    AlaaL about 13 years
    Yes sorry you are right I edited my code anyway and without using foreach if you don't want to use it