Click here to Skip to main content
15,886,724 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
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:
C#
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
Posted
Updated 25-Sep-14 3:06am
v3

What you need is to PIVOT your columns, try this article Pivot two or more columns in SQL Server 2005[^]
 
Share this answer
 
Comments
mit62 25-Sep-14 9:01am    
thanks a lot.I didn't know about pivot tables. But I need a solution in c# and I found it.
my solution is this:
C#
 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>
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900