I'm trying to figure out what would be the proper convention for LINQ when I need to do something like the following
- If there items, print them line-by-line
- If there are no items, print
"No items"
The way I would think to do it is like
if (items.Any())
{
foreach (string item in items)
{
Console.WriteLine(item);
}
}
else
{
Console.WriteLine("No items");
}
However, that would technically violate the principle of multiple enumeration. A way to not violate that would be
bool any = false;
foreach (string item in items)
{
any = true;
Console.WriteLine(item);
}
if (!any)
{
Console.WriteLine("No items");
}
but clearly, that is less elegant.