S h o r t S t o r i e s

// Tales from software development

C# List class with a case insensitive Contains() method

leave a comment »

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.

Advertisements

Written by Sea Monkey

June 15, 2012 at 8:00 pm

Posted in Development

Tagged with ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: