C# List class with a case insensitive Contains() method
Periodically I bump into a requirement for a List<string> class with a case-insensitive Contains() method. It’s happened several times over the past year and each time I do an internet search and find that no one seems to have come up with a good solution. As the only issue is with the Contains() method, I thought it might be worth running Reflector over the Contains() method to see if it could be easily re-implemented as a new method.
It turns out the the implementation is very simple but, interestingly, it handles null as a special case. It’s straightforward to implement a new method using the original code but with a case-insensitive StringComparer:
public class CaseInsensitiveStringList : List<string> { public CaseInsensitiveStringList() : base() { } public CaseInsensitiveStringList(int capacity) : base(capacity) { } public CaseInsensitiveStringList(IEnumerable<string> collection) : base(collection) { } /// <summary> /// Determines whether an item is in the list. /// </summary> /// <remarks> /// Note that this is a case insensitive and invariant culture comparison. /// </remarks> /// <param name="item">The item to locate in the list.</param> /// <returns>True if the item is in the list, otherwise false.</returns> public new bool Contains(string item) { if (item == null) { for (int j = 0; j < base.Count; j++) { if (base[j] == null) { return true; } } return false; } StringComparer comparer = StringComparer.CurrentCultureIgnoreCase; for (int i = 0; i < base.Count; i++) { if (comparer.Equals(base[i], item)) { return true; } } return false; } }
Alternatively, the class could be implemented with a constructor that takes a StringComparer argument similar to the the Dictionary<TKey, TValue>(IEqualityComparer<TKey>) constructor.
Leave a Reply