problem with comparing arraylists
hello there! I've got two arraylists named a1 and a2. I need to check if these two arraylists have the same contents. All I can think of is this------
Code:
for (int j = 0; j < a1.Count;j++ )
{
for (int i = 0; i < a2.Count; i++)
{
if
((a1[j])==(a2[i]))
{
return something................}
}
}
please help me find a solution
thanks in advance
lamiajoyee
Re: problem with comparing arraylists
Does the order of elements matter?
Re: problem with comparing arraylists
yes the order matters.and one more thing,the lists dont have to be the same,i need to check if certain elements are there in the list
Re: problem with comparing arraylists
First, don't use ArrayList if all your objects in the list are of equivalent type. Use List<T> instead; see the C# generics tutorial (link.
Second, to test for equality (for example):
Code:
for(int i = 0; i < a1.Count; i++)
{
//If any two elements aren't equal, the whole array isn't
if( a1[i] != a2[i] )
return false;
}
//Otherwise all the elements must have been equal
return true;
Similarly, suppose you had a different restriction like ("I require elements 6, 8, and 9 in a1 to be equal to elements 3, 7, and 12 in a2"). Then do:
Code:
public static bool compareRestriction(List<T> a1, List<T>a2)
{
return compareRestriction(a1, a2, new Tuple<int, int>[] {
new Tuple<int, int>(6,3),
new Tuple<int, int>(8,7),
new Tuple<int, int>(9,12) };
}
public static bool compareRestriction(List<T> a1, List<T> a2, Tuple<int, int>[] matchesRequired)
{
for(int i = 0; i < matches.Length; i++)
{
if( !(a1[matches[i].Item1].Equals(a2[matches[i].Item2])) )
return false;
}
return true;
}