ArrayList Search
In this chapter you will learn:
- How to search an ArrayList
- How to search from the end of an ArrayList
- How to search within a range of an ArrayList
Search for index
The following code searches for the first occurrence of the duplicated value.
using System;//from j a v a 2 s . c om
using System.Collections;
public class SamplesArrayList
{
public static void Main()
{
ArrayList myAL = new ArrayList();
myAL.Add( "the" );
myAL.Add( "quick" );
myAL.Add( "brown" );
myAL.Add( "fox" );
myAL.Add( "jumps" );
myAL.Add( "over" );
myAL.Add( "the" );
String myString = "the";
int myIndex = myAL.IndexOf( myString );
Console.WriteLine( "The first occurrence of \"{0}\" is at index {1}.", myString, myIndex );
}
public static void PrintIndexAndValues(IEnumerable myList)
{
int i = 0;
foreach (Object obj in myList)
Console.WriteLine(" [{0}]: {1}", i++, obj);
}
}
Search from the end
Search for the first occurrence of the
duplicated value in the last section of the ArrayList
.
using System;/* j av a2 s. c om*/
using System.Collections;
public class SamplesArrayList
{
public static void Main()
{
ArrayList myAL = new ArrayList();
myAL.Add( "the" );
myAL.Add( "quick" );
myAL.Add( "brown" );
myAL.Add( "fox" );
myAL.Add( "the" );
String myString = "the";
int myIndex = -1;
myIndex = myAL.IndexOf( myString, 4 );
Console.WriteLine(myIndex );
}
public static void PrintIndexAndValues(IEnumerable myList)
{
int i = 0;
foreach (Object obj in myList)
Console.WriteLine(" [{0}]: {1}", i++, obj);
}
}
Search inside a range
The following code shows how to
search for the first occurrence of the
duplicated value in a section of the ArrayList
.
using System;//ja v a2 s. c o m
using System.Collections;
public class SamplesArrayList
{
public static void Main()
{
ArrayList myAL = new ArrayList();
myAL.Add( "the" );
myAL.Add( "quick" );
myAL.Add( "brown" );
myAL.Add( "fox" );
myAL.Add( "jumps" );
myAL.Add( "over" );
myAL.Add( "the" );
myAL.Add( "lazy" );
myAL.Add( "dog" );
myAL.Add( "in" );
myAL.Add( "the" );
myAL.Add( "barn" );
String myString = "the";
int myIndex = -1;
myIndex = myAL.IndexOf( myString, 6, 6 );
Console.WriteLine( myIndex );
}
public static void PrintIndexAndValues(IEnumerable myList)
{
int i = 0;
foreach (Object obj in myList)
Console.WriteLine(" [{0}]: {1}", i++, obj);
}
}
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » List