0

Today I came across a LINQ extension method named All for List data type in C#. I have few statements to execute based on a condition. I have a list containing few strings. I will execute the statements after making sure that my list doesn't contain any empty or null elements. Here is how I can do it in two different ways using Any or All LINQ extension methods:

static void Main(string[] args)
{
    List<string> nameList = new List<string> { "foo", "bar","" };
    //way # 1
    if (!nameList.Any(x => string.IsNullOrEmpty(x)))
    {
       //do something here
    }
    //way # 2
    if (nameList.All(x => !string.IsNullOrEmpty(x)))
    {
       //do something here
    }
}

I've two questions here:

  1. Which is more efficient from implementation stand point of the extension method.
  2. Which looks better/appropriate from clean-code stand-point? As uncle Bob says - Clean code reads like well-written prose.
RBT
  • 24,161
  • 21
  • 159
  • 240
  • 2
    Is there a reason you're using `IsNullOrEmpty` in one but not the other, if you're simply talking about the difference between `Any` and `All`? – Rob Dec 13 '16 at 01:52
  • 1
    https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,1182 https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,1173 Compare it yourself (hint: they are identical*) – zerkms Dec 13 '16 at 01:54
  • @Rob - I fixed the code snippet. Thank you for pointing it out. – RBT Dec 13 '16 at 01:57

0 Answers0