Arik Rinberg Arik Rinberg - 5 months ago 59
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
I'd like to be able to receive

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


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));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download