0

I've found answers to determining if an IList<string> 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.

EDIT: As I'm using IList and not List, I don't have the function IndexOf, so the answer posted on here doesn't help me much :)

Thanks, Arik

Blue Granny
  • 772
  • 1
  • 8
  • 24
  • Possible duplicate of [How to ignore the case sensitivity in List](https://stackoverflow.com/questions/3107765/how-to-ignore-the-case-sensitivity-in-liststring) – Marko Juvančič Aug 28 '17 at 06:33
  • 2
    If you're sure there are no duplicates, a `Where()` followed by a `Single()` gives you a one line answer: `ilist.Where(l => l.ToLower() == element.ToLower()).Single()`. Otherwise, Mong's answer below helps if there is a possibility of a duplicate. [Here](https://stackoverflow.com/questions/21194750/which-is-faster-singlepredicate-or-wherepredicate-single) is some additional (probably not useful to you) info on why you should use `Where()` + `Single()` versus `Single(predicate)`. – Keyur PATEL Aug 28 '17 at 06:36
  • @MarkoJuvančič I'm using IList not List, so I don't have IndexOf function. I found that question but it didn't help much. – Blue Granny Aug 28 '17 at 07:19

1 Answers1

1

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 List<string> list, string value, StringComparer comparer)
{
    return list.FindIndex(i => comparer.Equals(i, value));
}

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

public static string CaseInsensitiveFind(this List<string> list, string value)
{
    return list.Find(i => StringComparer.CurrentCultureIgnoreCase.Equals(i, value));
}
Reddog
  • 15,219
  • 3
  • 51
  • 63
  • Thanks! This is what I was looking for! – Blue Granny Aug 28 '17 at 07:21
  • I'm unmarking as correct because of the need for try catch. As per this question: https://stackoverflow.com/questions/8687113/if-condition-vs-exception-handler I would like to avoid the necessity – Blue Granny Aug 28 '17 at 12:34
  • 1
    `FindIndex` returns a -1 value if the item doesn't exist and `Find` returns null. So I'm not sure I get why you might need try/catches... As per that linked question, indeed it seems you shouldn't want to throw any exceptions either. – Reddog Aug 28 '17 at 23:49