I have a List<string> with five strings in it:
abc
def
ghi
jkl
mno
I have another string, "pq", and I need to know if each string in the list does not start with "pq" - how would I do that with LINQ (.NET 4.0)?
Two options: Any
and All
. Which one you should use depends on what you find more readable:
var allNonPq = myList.All(x => !x.StartsWith("pq"));
var notAnyPq = !myList.Any(x => x.StartsWith("pq"));
These are effectively equivalent in efficiency - both will stop as soon as they reach an element starting with "pq" if there is one.
If you find yourself doing this a lot, you could even write your own extension method:
public static bool None<T>(this IEnumerable<T> source, Func<T, bool> predicate)
{
return !source.Any(predicate);
}
at which point you'd have:
var nonePq = myList.None(x => x.StartsWith("pq"));
Whether you find that more readable than the first two is a personal preference, of course :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With