Compare. Case

  • Thread starter Thread starter shapper
  • Start date Start date
S

shapper

Hello,

I am filtering items from a list as follows:

IQueryable<Account> students = accounts.Where(a => a.Roles.Contains
(givenRole)).AsQueryable();

Roles is a List<String>

How can I check if Roles.Contains givenRole ignoring case?
Which means that if Roles contains "Admin" then any givenRole as
"ADMIN", "Admin", "AdMin" would pass.

Thanks,
Miguel
 
shapper said:
Hello,

I am filtering items from a list as follows:

IQueryable<Account> students = accounts.Where(a => a.Roles.Contains
(givenRole)).AsQueryable();

Roles is a List<String>

How can I check if Roles.Contains givenRole ignoring case?
Which means that if Roles contains "Admin" then any givenRole as
"ADMIN", "Admin", "AdMin" would pass.

Most would use ToUpper() on the string to be checked and on the string
doing the checking to make them all the same case so that the check can't be
missed.
 
Hi,

You could use the overload of Contains that takes a StringComparer, for
example
IQueryable<Account> students = accounts.Where(a =>
a.Roles.Contains(givenRole,
StringComparer.InvariantCultureIgnoreCase)).AsQueryable();

Of course you could use a culture specific comparer if that better suites
your requirements, I simple used the Invariant comparer for the example.

Hope this helps
 
Most would use ToUpper() on the string to  be checked  and on the string
doing the checking to make them all the same case so that the check can'tbe
missed.

Except that using ToUpper() for case-insensitive comparison is a bad
idea, because it is not a lossless conversion (so strings that would
normally compare as not equal, even with case-insensitive comparison
enabled, may compare equal after ToUpper()). An example of a letter
that may trigger such behavior is "dotless I" in Turkish locale; see
http://en.wikipedia.org/wiki/Dotted_and_dotless_I

The correct way to perform case-insensitive comparisons, as Chris
demonstrated, is to use a comparison object with case-insensitive
semantics.
 
Back
Top