I'm writing out an aggregated list of statuses. It works fine except for the situation where there are none. At the moment, null is rendered and the position is empty.
item.Stuff.Where(e => Condition(e))
.Select(f => f.Status)
.Aggregate(String.Empty, (a, b) => a + b)
Now, I'd like to populate the table element with "---" in case the list is filtered down to an empty one by Condition but I can't decide on a method.
What would be a smooth way to approach it?
I've tried something like the atrocity below but it looks, well..., atrociously and it doesn't render right, neither. I get to see the actual source code line (preceded by False or True) instead of the values.
item.Stuff.Where(e => Condition(e)).Count() < 1
? "---"
: item.Stuff.Where(e => Condition(e))
.Select(f => f.Status)
.Aggregate(String.Empty, (a, b) => a + b)
You can use
DefaultIfEmpty(string.Empty).First();
MSDNExample
You could do something like this. If the status list is reasonably small (otherwise one should use StringBuilder anyway and not string concatenation).
It checks if the default text was replaced and, if it was, it concatenates the next status element to the already existing text mass.
This will return "---" if and only if it's never evaluated, i.e. if the list is empty. Otherwise one would get the same result as previously.
If
Status
is an enum, and you only need the distinct statuses, you can use the behavior of the [Flags] attribute.If you define the enum like this
you can just do:
The result is a collection of all statuses that are present in the list, and the output is nicely formatted list (
Active, Inactive, Pending
) orNone
if it's never run.