user3538475 user3538475 - 1 month ago 7
ASP.NET (C#) Question

How to convert table format to string programmatically

Good day all,

would like request to how to convert table format to string

eg:

Material Control August
Development September
Planning August
HR September


to

September: Development, HR

August : Material Control, Planning

List<String> returnvalueStringMonth = new List<String>();
List<String> returnvalueStringDept = new List<String>();
foreach (DataRow dr in dsSeries.Tables[0].Rows)
{
string newmanout = dr["MonthNames"].ToString();
returnvalueStringMonth.Add(newmanout);

string Departs = dr["Depart"].ToString();
returnvalueStringMonth.Add(Departs);
//var DDLName = dr["Depart"];
//Label dynamicLabel = new Label();
//dynamicLabel.Text = DDLName.ToString() + ",";
//div1.Controls.Add(dynamicLabel);
//var sumPlus = Convert.ToDouble(newmanout) +",";

}

List<string> b = new List<string>();
b.AddRange(returnvalueStringMonth.Distinct());
for (int cs = 0; cs < b.Count; cs++)
{
//Panel aspPanel = new Panel();
Label dynamicLabel = new Label();
dynamicLabel.Text = b[cs].ToString()+":" + "<br/>";
div1.Controls.Add(dynamicLabel);
}


I able achive until month only, then i realize made mistake.
So, please advise how to achive this.

Answer

The code below will fill a list of strings with your desired output. You can change the second loop to do what you want.

        var monthList = new Dictionary<String, List<String>>();
        foreach (DataRow dr in dsSeries.Tables[0].Rows)
        {
            var key = dr["MonthName"].ToString();
            var value = dr["Department"].ToString();
            if (!monthList.ContainsKey(key))
            {
                monthList.Add(key, new List<string>());
            }

            monthList[key].Add(value);
        }

        List<string> b = new List<String>();
        foreach (var month in monthList.Keys)
        {
            b.Add(month + ": " + String.Join(", ", monthList[month])");
        }