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:
- Which is more efficient from implementation stand point of the extension method.
- Which looks better/appropriate from clean-code stand-point? As uncle Bob says - Clean code reads like well-written prose.