How to add comma separated string into datatable in c#?

后端 未结 4 1912
北荒
北荒 2020-12-21 13:14

Let\'s consider I have two comma separated strings as written below.

string name = \"A,B,C,D\";
string value = \"100,200,300,400\";

So I wa

相关标签:
4条回答
  • 2020-12-21 13:59
    string[] names = name.split(',');
    string[] values = value.split(',');
    
    DataTable dt = new DataTable();
    dt.Columns.Add("name");
    dt.Columns.Add("value");
    
    int cnt = names.length;
    for(int i=0; i<cnt; i++)
    {
      DataRow dr = dt.NewRow();
      dr["name"] = names[i];
      dr["value"] = values[i];
    }
    
    0 讨论(0)
  • 2020-12-21 14:06

    try this:

      string[] name = "A,B,C,D".Split(',');
               string[] value = "100,200,300,400".Split(',');
                 DataTable tbl = new DataTable();
                 tbl.Columns.Add("name", typeof(string));
                 tbl.Columns.Add("value", typeof(string));
                for( int i=0; i<name.Length;i++)
                {
    
                     tbl.Rows.Add(name[i],value[i]);
                }
    
    0 讨论(0)
  • 2020-12-21 14:08

    split sourse strings and add to datatable

        DataTable table = new DataTable();
        table.Columns.Add("name", typeof(string));
        table.Columns.Add("value", typeof(string));
    
        table.Rows.Add("nameStr", "valueStr");
    
    0 讨论(0)
  • 2020-12-21 14:11

    Try something like this:

    DataTable table = new DataTable();
    table.Columns.Add("name", typeof(string));
    table.Columns.Add("value", typeof(string));
    
    string name = "A,B,C,D";
    string value = "100,200,300,400";
    
    string[] names = name.Split(',');
    string[] values = value.Split(',');
    
    for(int i=0; i<names.Length; i++)
        table.Rows.Add(new object[]{ names[i], values[i] });
    

    But you should implement some validation code to make it more appropriate.

    0 讨论(0)
提交回复
热议问题