user1154207
user1154207

Reputation:

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

Upvotes: 0

Views: 7936

Answers (3)

Desolator
Desolator

Reputation: 22739

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();
    }

}

Upvotes: 0

vcsjones
vcsjones

Reputation: 141588

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.

Upvotes: 1

SLaks
SLaks

Reputation: 887195

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

Upvotes: 5

Related Questions