Click here to Skip to main content
14,735,324 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:
test akshay
test sameer
test sidd
Hi som

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

test akshay,sameer,sidd
Hi som.

How can i get this??


1 solution

You need two foreach loops: One to collect the values, and one to output them.
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));
        dict[msg].AppendFormat(",{0}", to);
foreach (string key in dict.Keys)
    Console.WriteLine("{0} {2}", key, dict[key].ToString());

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