在 foreach 数据行中分隔数据

Separating data within a foreach datarow

我需要这样显示我的数据:

任务到期

无截止日期

我需要将有截止日期的任务和没有截止日期的任务分开(如果没有日期,截止日期字段为空)。我能够做到,但我不确定这是正确的方法。有没有办法做到这一点,如果没有没有截止日期的任务,我可以隐藏 "No Due Date" header?

Dictionary<string, List<DataRow>> userEmailList = new Dictionary<string, List<DataRow>>();

foreach (DataRow row in dt.Rows)
{
    string email = row["AssignedToEmail"].ToString();

    if (!userEmailList.ContainsKey(email))
    {
        userEmailList.Add(email, new List<DataRow>());
    }
    userEmailList[email].Add(row);
}
string dueDate = "";
foreach (string emailAddy in userEmailList.Keys)
{
    StringBuilder sb = new StringBuilder();
    sb.Append("<html><head></head><body>");
    sb.Append("<h2>Tasks Due</h2><ul>");
    foreach (DataRow row in userEmailList[emailAddy])
    {
        if (!String.IsNullOrEmpty(row["dueDate"].ToString()))
        {
            dueDate = Convert.ToDateTime(row["dueDate"]).ToShortDateString();
            sb.AppendFormat("<li><strong>{0}</strong> - {1}</li>", dueDate, row["details"].ToString());
        }
    }
    sb.Append("</ul><h2>No Due Date</h2><ul>");
    foreach (DataRow row in userEmailList[emailAddy])
    {
        if (String.IsNullOrEmpty(row["dueDate"].ToString()))
        {
            sb.AppendFormat("<li>{0}</li>", row["details"].ToString());
        }
    }
    sb.Append("</ul></body><html>");
}

使用两个 StringBuilder 也可以消除对两个循环的需要

    foreach (string emailAddy in userEmailList.Keys)
    {
        StringBuilder sbDue = new StringBuilder();
        StringBuilder sbNotDue = new StringBuilder();
        sbDue.Append("<html><head></head><body>");
        sbDue.Append("<h2>Tasks Due</h2><ul>");
        foreach (DataRow row in userEmailList[emailAddy])
        {
            if (!String.IsNullOrEmpty(row["dueDate"].ToString()))
            {
                dueDate = Convert.ToDateTime(row["dueDate"]).ToShortDateString();
                sbDue.AppendFormat("<li><strong>{0}</strong> - {1}</li>", dueDate, row["details"].ToString());
            }
            else
                 sbNotDue.AppendFormat("<li>{0}</li>", row["details"].ToString());
        }
        if(sbNotDue.Length > 0)
        {
           sbNotDue.Insert("<h2>No Due Date</h2><ul>");
           sbDue.Append(sbNotDue.ToString());
        } 

        sbDue.Append("</ul></body><html>");
    }