简体   繁体   中英

How to make use of Case-Insensitive Contains in ArrayList

This is my code in ASP.Net C#

ArrayList myArrayList = new ArrayList();
            myArrayList.Add("Apple");
            myArrayList.Add("Banana");

            if (myArrayList.Contains("apple"))  // This returns false because Contains doesn't support a case-sensitive search
                statusLabel.Text = "ArrayList contains apple";

I get false , Since Apple not equals apple. I have even tried like

myArrayList.Contains("apple", StringComparer.OrdinalIgnoreCase)

But intellisense shows error. Is this really possible on ArrayList ?apple

You should use List<string> instead of ArrayList .
Your code will then work as-is.

If you are using .NET 1.1 because Generics aren't available, you could do something like this:

bool contains = false;
for (int i = 0; i < myArrayList.Count && !contains; i++)
{
    contains = ((string)myArrayList[i]).ToUpper() == "APPLE";
}
if (contains)
{
    statusLabel.Text = "ArrayList contains apple";
}

Otherwise, using List<string> instead of ArrayList, then myArrayList.Contains("apple", StringComparer.OrdinalIgnoreCase) will work.

If you have .NET 2 + Generics available to you; then there really is no good reason to be using the ArrayList anymore.

personally I'd prefer to use this function rather than lowering the whole string..

public static class StringExtensions
{
    /// <summary>
    /// Allows case insensitive checks
    /// </summary>
    public static bool Contains(this string source, string toCheck, StringComparison comp)
    {
        return source.IndexOf(toCheck, comp) >= 0;
    }
}

EDIT: usage of the code..

ArrayList myArrayList = new ArrayList();
            myArrayList.Add("Apple");
            myArrayList.Add("Banana");

foreach(var item in myArrayList)
{
    if(StringExtensions.Contains(statusLabel.Text, item.ToString(), StringComparison.OrdinalIgnoreCase)
    {
       //true.. do whatever you want in here...
       statusLabel.Text = "ArrayList contains " + item.ToString();
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM