Click here to Skip to main content
15,891,761 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a data table.
In that I have two columns like "MSG" and "TO".
For a single message ..I have multiple "TO" records.
For eg:
MSG TO
test akshay
test sameer
test sidd
Hi som

Now using for each loop i want all "TO" as comma separated.
for eg:

MSG TO
test akshay,sameer,sidd
Hi som.

How can i get this??

Thanks-Akshay
Posted

1 solution

You need two foreach loops: One to collect the values, and one to output them.
C#
Dictionary<string, StringBuilder> dict = new Dictionary<string, StringBuilder>();
foreach (DataRow row in dt.Rows)
    {
    string msg = (string)row["MSG"];
    string to = (string)row["TO"];
    if (!dict.ContainsKey(msg))
        {
        dict.Add(msg, new StringBuilder(to));
        }
    else
        {
        dict[msg].AppendFormat(",{0}", to);
        }
    }
foreach (string key in dict.Keys)
    {
    Console.WriteLine("{0} {2}", key, dict[key].ToString());
    }
 
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