如何在数据表的特定列中找到相同的值并合并其他colmns? [英] How do I find same values in a specific column of a datatable and merge their other colmns ?
问题描述
例如我的数据表是这样的:
dt1:
code |号码
-----------
A | 12
B | 1
A | 4
A | 2
B | 5
假设数据表2有4列。我需要一个数据表甚至是这样的列表:
dt2:
代码| Number1 | Number2 | Number3
---------------------------------
A | 12 | 4 | 2
B | 1 | 5 |
未完成的代码:
for example my data table is like this:
dt1:
code| Number
-----------
A | 12
B | 1
A | 4
A | 2
B | 5
Assume that datatable 2 has 4 column.I need a datatable or even list like this:
dt2:
code| Number1|Number2 | Number3
---------------------------------
A | 12 | 4 | 2
B | 1 | 5 |
my uncompleted code:
DataTable dt1 = ds.Tables[0];
for(int i=0;i< dt1.Rows.Count;i++)
{
string code=dt1.Rows[i].ItemArray[0].ToString();
bool existence=false;
for(int j=0;j< dt2.Rows.Count;j++)
{
if(dt2.Rows[j]["code"]==code)
{
existence=true;
//add dt1[i]["number"] to dt2[j][next columns which is not filling]????
break;
}
}
if(!existence)//not existence
{
//dt2.add(dt1.row[i])
}
}
我不喜欢我不知道如何编写我上面确定的第一条评论
以及是否有另一种简单的方法来解决这个问题
I don't know how to code the first comment I determine above
and if there is another simple way to solve this question
推荐答案
你是什么需要是PIVOT你的专栏,试试这篇文章转轴两个或更多SQL Server 2005中的列 [ ^ ]
What you need is to PIVOT your columns, try this article Pivot two or more columns in SQL Server 2005[^]
试试这个
http://dba.stackexchan ge.com/questions/30119/pivot-rows-into-multiple-columns [ ^ ]
我的解决方案是:
my solution is this:
DataTable dttmp = ds.Tables[0];
var dic = new Dictionary<String,List<String>>();
for (int i = 0; i < dttmp.Rows.Count; i++)
{
string code = dttmp.Rows[i].ItemArray[0].ToString();
string time = dttmp.Rows[i].ItemArray[1].ToString();
if (code != "0")
{
if (!dic.ContainsKey(code))
dic.Add(code, new List<string>(){time});
else
dic[code].Add(time);
}
}
</string>
这篇关于如何在数据表的特定列中找到相同的值并合并其他colmns?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!