Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 832
rustyBucketBay Avatar asked Oct 15 '25 14:10

rustyBucketBay


2 Answers

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.

like image 70
canton7 Avatar answered Oct 17 '25 05:10

canton7


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.

like image 28
Tim Schmelter Avatar answered Oct 17 '25 06:10

Tim Schmelter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!