I have a function that returns a list of email addresses from a SQL stored Proc based on an ID called. It is using StringBuilder and returns one column. For most IDs there are 4 or less email addresses and this format is fine. However we are now getting more IDs with 10+ email addresses and this is making the page too long.
The function is:
DataTable dt = DAL.ExecStoredProc(DAL.DatabaseName.DB, "storedProc", param);
StringBuilder sb = new StringBuilder();
sb.Append("<br/><br/>");
sb.Append("<table border='0' cellpadding='3'>");
for (int i = 0; i < dt.Rows.Count; i++)
{
sb.Append("<tr><td>");
sb.Append(dt.Rows[i]["EMail"].ToString());
sb.Append("</td></tr>");
}
sb.Append("</table>");
return sb.ToString();
I have tried using the following but it breaks when there are too few addresses to return:
DataTable dt = DAL.ExecStoredProc(DAL.DatabaseName.DB, "storedProc", param);
StringBuilder sb = new StringBuilder();
sb.Append("<br/><br/>");
sb.Append("<table border='0' cellpadding='3'>");
for (int i = 0; i < dt.Rows.Count; i++)
{
sb.Append("<tr><td>");
sb.Append(dt.Rows[i]["EMail"].ToString());
i++;
sb.Append("</td>");
sb.Append("<td>");
sb.Append(dt.Rows[i]["EMail"].ToString());
i++;
sb.Append("</td>");
sb.Append("<td>");
sb.Append(dt.Rows[i]["EMail"].ToString());
i++;
sb.Append("</td></tr>");
}
sb.Append("</table>");
return sb.ToString();
Using Linq’s
Takefunction, you could replace the following block of code from your first example:with this:
Since Take returns up to the specified number of elements from the beginning of the sequence, this block of code will be run anywhere from 0 to 3 times. You’ll have 3 addresses displayed at most (even if more are present), and you won’t get an
IndexOutOfRangeExceptionif you have less than 3.UPDATE: ASP.NET 2.0 Compatible
Since you can’t use Linq, this should have the same result:
The expression
dt.Rows.Count > 3 ? 3 : dt.Rows.Countuses the?operator to cause theforloop to iterate over all of the email addresses unless there are more than 3, in which case it will iterate only 3 times.