Building table from string c #
Ok, so I have a table <tr>
built from a string that looks something like this:13467
1= monday
2= tuesday
...
7= sunday
so 13467 = mon,wed,thurs,sat,sun
My existing code has manually checked the line like
if (breakfastDays.Contains("1")) {
sb.Append("<td class=\"active\"> </td>");
mo++;
} else {
sb.Append("<td> </td>");
}
if (breakfastDays.Contains("2")) {
sb.Append("<td class=\"active\"> </td>");
tu++;
} else {
sb.Append("<td> </td>");
}
The part class="active"
just tells css
to check the box.
Is there an easier way to perform string validation?
Maybe some loops for-in
might be?
source to share
Yes, you can use a loop. The only tricky thing is the variables you are incrementing, it would be easier if you used an array for that.
for (char c = '1'; c <= '7'; c++) {
if (breakfastDays.Contains(c)) {
sb.Append("<td class=\"active\"> </td>");
switch (c) {
case '1': mo++; break;
case '2': tu++; break;
case '3': we++; break;
case '4': th++; break;
case '5': fr++; break;
case '6': sa++; break;
case '7': su++; break;
}
} else {
sb.Append("<td> </td>");
}
}
source to share
I think mo
and tu
count the number of days of the week. The best way might be an array:
public static void Main()
{
int[] breakfastDays = new int[7];
string days = "13467";
var sb = new StringBuilder();
for (int i = 0; i < 7; i++)
{
if (days.Contains((i + 1).ToString()))
{
sb.Append("<td class=\"active\"> </td>");
breakfastDays[i]++;
} else {
sb.Append("<td> </td>");
}
}
Console.WriteLine(sb.ToString());
}
This way, you don't need separate variables for each day.
source to share
I'll see first if you can get rid of the individual variables for the day counters that seem clunky and prone to problems. This, and reducing it to a simple loop, something like:
// Set up buckets for each day, with an initial count of 0
var dayMap = "1234567".ToDictionary(c => c, c => 0);
// For each key ("day")...
foreach (var day in dayMap.Keys.ToList())
{
// Start writing the cell
sb.Append("<td");
// Check if input string contains that key
if (breakfastDays.Contains(day))
{
// Increment the value in our day bucket
dayMap[day]++;
// Make the cell "active"
sb.Append(" class=\"active\"");
}
// Finish writing the cell
sb.Append("> </td>");
}
source to share
This will fix the problem of writing seven tests for a table:
for (int i = 1; i <= 7; i++)
{
if (breakfastDays.Contains(i.ToString())
{
sb.Append("<td class=\"active\"> </td>"));
}
else
{
sb.Append("<td> </td>");
}
}
We could be more clever, but I do not want to miss the importance of mo++
, and tu++
in your code.
source to share