Click here to Skip to main content
15,915,501 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have this table

Table_Items

Item_ id---Item
1---------a
1---------b
1---------c
1---------d
2---------e
2---------f
3---------g
4---------h


How can i loop through this list and get results something like this;

item id and all items for that ID.

for example, 1,a,b,c,d
2,e,f
3,g
4,h
Posted
Updated 8-Oct-13 18:51pm
v2

SQL
select Item_ id,
  stuff((SELECT distinct ', ' + cast(Item as varchar(10))
           FROM Table_Items t2
           where t2.Item_ id= t1.Item_ id
           FOR XML PATH('')),1,1,'') as Item
from Table_Items t1
group by Item_ id
 
Share this answer
 
C#
// if you fetch all data from sql table into DataTabl dt; then use this logic 
//otherwise use Solution 1 

            DataTable dt = new DataTable();
            string item_id = string.Empty;
            DataRow[] datarows =  dt.Select("item_id = '" + item_id + "'");

            string result = item_id;

            foreach (DataRow dr in datarows)
            {
                result += "," + dr["Item"].ToString();
            }

            //you can use result;
            //TODO:
            Console.WriteLine(result);
 
Share this answer
 

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