Compare. Case

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
 
M

Mr. Arnold

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.
 
C

Chris Taylor

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
 
P

Pavel Minaev

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top