I have a List<string> with five strings in it:
abc
def
ghi
jkl
mno
I have another string, "pq", and I nee开发者_如何学编程d 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 :)
bool noPQStart = !myList.Any( x=> x.StartsWith("pq"));
This will produce results which is an IEnumerable<bool>
var strings = new string[] { ... };
var results = strings.Select(s => s.StartsWith("pq"));
var notPq = from s in myList where !s.StartsWith("pq") select s;
if (notPq.Any()) {
// At least one item in list doesn't start with pq, possibly do something with each element that doesn't
}
精彩评论