0

Let us say I have this code:

private readonly static List<string> ExtPos = new List<string> {".dat", ".wef"};

private static int ExtToPos(string ext)
{
    return ExtPos.IndexOf(ext /*, StringComparer.InvariantCultureIgnoreCase*/);
}

How can I ignore the letter case in content search?

Thanks

Georg
  • 1,946
  • 26
  • 18

2 Answers2

2

You could use FindIndex:

int ix = ExtPos.FindIndex(x => ".DAT".Equals(x, StringComparison.CurrentCultureIgnoreCase));

Or you could use the StringComparer: it's more "resistant" to null (note how I built the previos comparison: I put the "100% not-null because it's a fixed string" value on the left of the Equals!)

int ix = ExtPos.FindIndex(x => StringComparer.CurrentCultureIgnoreCase.Equals(".DAT", x));
xanatos
  • 109,618
  • 12
  • 197
  • 280
  • FindIndex works perfect, thank you! (I got String.Compare(ext, x, StringComparison.CurrentCultureIgnoreCase) == 0 as predicate) – Georg Feb 24 '15 at 13:24
  • @Georg Using `Compare` and then `== 0` feels a bit wrong. It is better to use `Equals` in that case (it returns a `bool` right away). You could consider using `OrdinalIgnoreCase`. The default for equality checks with strings is an ordinal comparison, so if you want "equality like usually, only case-insensitive", you might prefer `OrdinalIgnoreCase`. – Jeppe Stig Nielsen Feb 24 '15 at 13:46
  • That's right, Compare == 0 looks a bit strange, "Equals" is much better for those applying. "CurrentCultureIgnoreCase" I unfortunate taken from xanatos, usually I use the faster ordinal-comparison. – Georg Feb 25 '15 at 19:55
0

Use the FindIndex method. Like this:

private static int ExtToPos(string ext)
{
    return ExtPos.FindIndex(_ => 
        string.Equals(_, ext, StringComparison.InvariantCultureIgnoreCase));
}
Mårten Wikström
  • 11,074
  • 5
  • 47
  • 87