How to Search for an Item in an ASP.NET C# ArrayList

 
Written by Mark Pringle |
Published on:

Searching for an item in a C# ArrayList is fairly simple. The only thing you need to do is loop through the ArrayList. Once the item in the collection is found, you break out of the loop. In the example below, if the item you are searching for is not found, I return a "not found" message.

First, I am using the Use the Add() method or object initializer syntax to add elements in an ArrayList. When I run the application, I use the console application and a C# Console.ReadLine() method to take input from the user. 

using System.Collections;

namespace ConsoleAppFun
{
    class Examples
    {
        static void Main()
        {
            ArrayList AddSyllables = new ArrayList();
            AddSyllables.Add("ia");
            AddSyllables.Add("riet");
            AddSyllables.Add("dien");
            AddSyllables.Add("ien");
            AddSyllables.Add("iet");
            AddSyllables.Add("iu");
            AddSyllables.Add("iest");
            AddSyllables.Add("io");
            AddSyllables.Add("ii");
            AddSyllables.Add("ily");
            AddSyllables.Add(@".oala\b");
            AddSyllables.Add(@".iara\b");
            AddSyllables.Add(@".ying\b");
            AddSyllables.Add(".earest");
            AddSyllables.Add(".arer");

            string found = "was not found";
            string searchString = Console.ReadLine();

            foreach (string item in AddSyllables)
            {
                if (item == searchString?.Trim())
                {
                    found = "was found";                    
                    break;
                }
            }
            Console.WriteLine("This string " + found + " in the array: " + searchString);
        }
    }
}

If I type iest into the console app, this is the found message I receive. 

search found in arraylist

If I type ilikepickles into the console app, this is the not found message I receive. 

search not found in arraylist

That's it!

Copyright © TravelDailyLife.com

Author: Mark Pringle
I'm just a guy who is addicted to the unfamiliar and who fulfills this addiction by traveling and writing about my travels. As a lover of sports, penning opinion articles related to sports is also a pastime.
My External Website (External Website Opens in New Window)

Comments

Please Login to Comment
No comments have been posted. Be the first.



Hire a Writer