Joining Values Of Two Columns From DataTable

守給你的承諾、 提交于 2020-01-23 10:59:05

问题


Joining Values Of Two Columns From DataTable Two columns make it in one columns from datatable

my datatable is

   TagNumber, LogNumber  Combined
    124           1         2
    125           1         3
    126           2         4
o/p:

     TagNumber 
    124 ~1~2          
    125 ~1~3         
    126 ~2~4         
 combined column is merge from column0 and column1

i dont understand hw can i do please write sample of code

I dont have experience on linq . I add column bt hw can i merge two columns in that one columns

I got answer:

For i As Integer = 0 To dstemp.Tables(0).Rows.Count - 1
dstemp.Tables(0).Rows(i)(0) = dstemp.Tables(0).Rows(i)("TagNumber") & "~" &      dstemp.Tables(0).Rows(i)("LogNumber") & "~" & dstemp.Tables(0).Rows(i)("Combined")
next

回答1:


Ok if you really want to do this then you have create a extra DataTable with Three Columns:

TagNumber, LogNumber Combined: as below:

private DataTable CreateDataTableColumns()
{
    DataTable dtThreeItems = new DataTable();
    dtThreeItems.Columns.Add("TagNumber", typeof(String));
    dtThreeItems.Columns.Add("LogNumber", typeof(String));
    dtThreeItems.Columns.Add("Combined", typeof(String));
    return dtThreeItems;
}

Now iterate the old datatable as below to get combined value:

foreach (DataRow dr in dtTwoItems.Rows)
            {
                row = dtThreeItems.NewRow();
                row["TagNumber"] = dr["TagNumber"].ToString();
                row["LogNumber"] = dr["LogNumber"].ToString();
                row["Combined"] = dr["TagNumber"].ToString()+"/"+dr["LogNumber"].ToString() ;
                dtThreeItems.Rows.Add(row);
            }

Thats All




回答2:


Try doing it like this.

 dtTwoItems.Columns.Add("Combined", typeof(string), "TagNumber+'/'+LogNumber");



回答3:


DataTable is like a container. It is not proper to join tables.

I recommend you'd use linq.




回答4:


Did you try to Add new Column to DataTable and then iterate through Each Row to put value by combining them?

EDIT: I Am not sure if Linq or Datatable query have some inbuilt feature to do this, but simple solution is what I tell. Or if you are filling your datatable from any SQL Query based database, then write a SQL that has third column with merged value using concat of columns.

Edit2:

foreach (Datarow r in myTable.Rows) {
   r["Newcolumn"] = Convert.ToString(r["c1"]) + "/" + Convert.ToString(r["c2"]);
}


来源:https://stackoverflow.com/questions/18140445/joining-values-of-two-columns-from-datatable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!