Multiple Listing and Using Any ()

I am trying to figure out what will be the correct LINQ convention when I need to do something like the following

  • If there are items, print them one at a time.
  • If there are no items, type "No items"

The way I thought to do this seems to be

if (items.Any())
{
    foreach (string item in items)
    {
        Console.WriteLine(item);
    }
}
else
{
    Console.WriteLine("No items");
}

However, this will technically violate the principle of multiple enumeration. A way not to break it will be

bool any = false;
foreach (string item in items)
{
    any = true;
    Console.WriteLine(item);
}   
if (!any)
{
    Console.WriteLine("No items");
}

but it is clear that he is less elegant.

+4
source share
3 answers

Since we are talking about LINQ, what about the LINQ solution?

foreach (var item in items.DefaultIfEmpty("No items"))
    Console.WriteLine(item);
+4
source
var itemsList = items as List<Item> ?? items.ToList();

IEnumerable<Item> , . , .ToList(). . (Resharper . .)

0

This may or may not be a problem, depending on your use case, since Any () will short-circuit as soon as the condition is met, which means that all IEnumerable does not need to be listed.

Check out the comments below, which indicate potential pitfalls, such as an implementation, just ahead or expensive.

Here's a reference source :

public static bool Any<TSource>(this IEnumerable<TSource> source) {
    if (source == null) throw Error.ArgumentNull("source");
    using (IEnumerator<TSource> e = source.GetEnumerator()) {
        if (e.MoveNext()) return true;
    }
    return false;
}
-1
source

Source: https://habr.com/ru/post/1694004/


All Articles