C# 连接数据表中两列的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18140445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Joining Values Of Two Columns From DataTable
提问by Harsh
Joining Values Of Two Columns From DataTableTwo 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
我没有 linq 的经验。我添加列 bt hw 我可以合并那一列中的两列吗
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
采纳答案by Ram Singh
Ok if you really want to do this then you have create a extra DataTable with Three Columns:
好的,如果你真的想这样做,那么你已经创建了一个额外的三列数据表:
TagNumber, LogNumber Combined: as below:
TagNumber, LogNumber 组合:如下:
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
就这样
回答by Sumit Gupta
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.
编辑:我不确定 Linq 或 Datatable 查询是否有一些内置功能可以做到这一点,但我告诉的是简单的解决方案。或者,如果您要从任何基于 SQL 查询的数据库填充数据表,请编写一个 SQL,该 SQL 使用列的连接来编写具有合并值的第三列。
Edit2:
编辑2:
foreach (Datarow r in myTable.Rows) {
r["Newcolumn"] = Convert.ToString(r["c1"]) + "/" + Convert.ToString(r["c2"]);
}
回答by carbonara
DataTable is like a container. It is not proper to join tables.
DataTable 就像一个容器。连接表是不合适的。
I recommend you'd use linq.
我建议你使用 linq。
回答by Nil
Try doing it like this.
尝试这样做。
dtTwoItems.Columns.Add("Combined", typeof(string), "TagNumber+'/'+LogNumber");