views:

92

answers:

4

Hi all,

I want to do a search of a list of strings, non cap sensitive.

Have tried .Contains and ==

Is there a method to do this, or would I have to convert the entire list of strings to noncaps, then search?

Cheers!

A: 

How about String.IndefOf with the StringComparison argument set? Alternatively, build a RegEx.

micahtan
+3  A: 

One way to do it.

var answer = list.FirstOrDefault(item => item.Equals("test", StringComparison.CurrentCultureIgnoreCase));
nullptr
You will end up with NullReferenceException here easily when item is null.
Dmytrii Nagirniak
Do this to make it null safe: `"test".Equals(item, StringComparison.CurrentCultureIgnoreCase)`.
Andrew Hare
where does FirstOrDefault come from
baron
@Andrew, for this particular sample it will work. But you cannot make it null safe that way if both instance and argument can be null. So it is better to use String.Compare.
Dmytrii Nagirniak
FirstOrDefault is an extension method in System.Linq.Enumerable
nullptr
+2  A: 

Assuming you use C# 3:

var all = new [] {"A", "a", "AB", "aB", "Ab". "Etc"};
var searchItem = "A";
var found = all.Where (x => string.Compare(x, searchItem, StringComparison.InvariantCultureIgnoreCase) == 0);

foreach(var foundItem in found)
  Console.WriteLine(foundItem);
Dmytrii Nagirniak
A: 

You can simply use String.ToUpper() to compare as non sensitive. (Just uppercase both strings you're comparing).

Or there are more advanced string comparison helpers in the .net lib:

See: http://en.csharp-online.net/CSharp%5FFAQ%3A%5FHow%5Fperform%5Fa%5Fcase%5Finsensitive%5Fstring%5Fcomparison

Crowe T. Robot
This generally isn't a good idea, especially if you making many comparisons. Because strings are immutable a temporary string must be created to make the comparison.
Phaedrus