-
November 25th, 2011, 01:49 AM
#1
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
-
November 25th, 2011, 03:53 AM
#2
Re: problem with comparing arraylists
Does the order of elements matter?
- Make it run.
- Make it right.
- Make it fast.
Don't hesitate to rate my post.
-
November 25th, 2011, 04:16 AM
#3
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
Last edited by lamiajoyee; November 25th, 2011 at 04:19 AM.
-
November 26th, 2011, 12:09 PM
#4
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;
}
Best Regards,
BioPhysEngr
http://blog.biophysengr.net
--
All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|