Link to home
Start Free TrialLog in
Avatar of R8VI
R8VI

asked on

Compare array list to a string, asp.net, c#

Hi,

I have the following code

 while (rdrEUrls.Read())
                            {
                                string requrls = rdrEUrls["requrl"].ToString();
                                GetalldUrlsFromDase.Add(requrl);


                            }

where GetalldUrlsFromDase is an array list

what i want to do is i have a string called X which has a value I want to loop through the whole array list and check if the value of x is in the array list. if it is then do nothing if it isnt then lbltext="Something there"

please help.

Thanks.

R8VI
Avatar of angus_young_acdc
angus_young_acdc
Flag of United Kingdom of Great Britain and Northern Ireland image

Try this (assuming your arraylist is full of strings, if not just do .To.String())
            string X = "The string you want to check for";
            foreach (string obj in myArrayListName)
            {
                if (X == obj)
                {
                    // do whatever processing you wish
                }
            }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Avodah
Avodah
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
First two lines now included
ArrayList alst = new ArrayList();
string X = "a string";
 
// Option 1
int index = alst.BinarySearch(X, delegate(object a, object b) { return String.Compare(a, b, true); });
 
if (index < 0)
{
    lbltext="Something there"
}
 
// Option 2
bool found = false;
foreach(string item in alst)
{
    if (String.Compare(X, item, true) == 0)
    {
        found = true;
        break;
    }
}
 
if (!found)
{
    lbltext="Something there"
}

Open in new window

Don't use ArrayList at all, it's practically obsolete. Use a generic list of strings:

List<string> urls = new List<string>();
while (rdrEUrls.Read()) {
   string requrls = rdrEUrls["requrl"].ToString();
   urls.Add(requrl);
}

Now you don't have to loop through the list yourself to look for a value, there are ready made methods for that:

if (!urls.Contains(X)) {
   lbltext="Something there"
}

If you are doing a lot of lookups in the list, you could use a dictionary instead, as it's a lot faster to look for a key in a dictionary:

Dictionary<string,int> urls = new Dictionary<string,int>();
while (rdrEUrls.Read()) {
   string requrls = rdrEUrls["requrl"].ToString();
   if (!url.ContainsKey(requrl)) {
      urls.Add(requrl, 0);
   }
}

Now checking for a string is practically instant, even if you would have a million strings in the dictionary.

if (!urls.ContainsKey(X)) {
   lbltext="Something there"
}