rustyBucketBay
rustyBucketBay

Reputation: 4561

linq contains string comparison. IEqualityComparer

I want to know if a determind string is in a string list, with the StringComparison.InvariantCultureIgnoreCase criteria. So I tried something like:

bool isInList = _myList.Contains(toFindString, StringComparison.InvariantCultureIgnoreCase);

Or:

bool isInList = _myList.Contains(listElement => listElement .Equals(toFindString,StringComparison.InvariantCultureIgnoreCase));

But, the Contains method does not contain the Func<TSource, bool> predicate overload which I think is the cleanest for this case. The Where or the Count method for example got it.

Overload method signature for Count:

public static int Count<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

Specific application for my case:

int foundCount = _myList.Count(listElement => listElement.Equals(toFindString, StringComparison.InvariantCultureIgnoreCase));

What would be the cleanest way to add the StringComparison.InvariantCultureIgnoreCase criteria to the linq Contains current overload with the IEqualityComparer that is this one public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value, IEqualityComparer<TSource> comparer);?

Upvotes: 3

Views: 4054

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460158

Either use StringComparer.InvariantCultureIgnoreCase

bool isInList = _myList.Contains(toFindString, StringComparer.InvariantCultureIgnoreCase);

or use Any with StringComparison:

bool isInList = _myList.Any(s => s.Equals(toFindString,StringComparison.InvariantCultureIgnoreCase));

the latter has a problem if there are null-strings in the list, so you could use string.Equals.

Note that both ways are not suppported with Linq-To-Entities.

Upvotes: 5

canton7
canton7

Reputation: 42245

You've got several options.

The first is to use Enumerable.Any, and test each element using the string.Equals overload which takes a StringComparison:

bool isInList = _myList.Any(x => string.Equals(x, "A", StringComparison.InvariantCultureIgnoreCase));

(It's safer to use the static string.Equals(string, string) where possible, as it's safe to either argument being null).

Linq also provides an overload of Contains which takes an IEqualityComparer<T>, which you can pass StringComparer.InvariantCultureIgnoreCase to:

bool isInList = _myList.Contains("A", StringComparer.InvariantCultureIgnoreCase);

See here.

Upvotes: 5

Related Questions