Arik Rinberg Arik Rinberg - 2 months ago 34
C# Question

C# - Find case insensitive index in IList

I've found answers to determining if an IList contains an element using case insensitive contains:

ilist.Contains(element, StringComparer.CurrentCultureIgnoreCase)


But what I would like to do is find the element itself that corresponds within the IList to the element I'm searching for. For instance if the IList contains
{Foo, Bar}
and I search for
fOo
I'd like to be able to receive
Foo
.

I'm not worried about multiples, and the IList doesn't seem to contain any function other than
IndexOf
with doesn't help me much.

Thanks,
Arik

Answer Source

To find the index of the item you could use the FindIndex function with a custom predicate doing the case-insensitve match. Similarly, you can use Find to get the actual item.

I'd probably create an extension method to use as an overload.

public static int IndexOf(this IList<string> list, string value, StringComparer comparer)
{
    return list.FindIndex(i => comparer.Equals(i, value));
}

public static int CaseInsensitiveIndexOf(this IList<string> list, string value)
{
    return IndexOf(list, value, StringComparer.CurrentCultureIgnoreCase);
}

public static string CaseInsensitiveFind(this IList<string> list, string value)
{
    return list.Find(i => StringComparer.CurrentCultureIgnoreCase.Equals(i, value));
}