Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ does not start with on List<string>

Tags:

string

linq

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)?

like image 421
Snowy Avatar asked May 05 '11 20:05

Snowy


1 Answers

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 :)

like image 89
Jon Skeet Avatar answered Sep 28 '22 19:09

Jon Skeet