Sign in to follow this  

[.net] Anyone a guru with C# Lists?

This topic is 3725 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I have a list and i want to iterate through it and compare each object in the list with every other object in the list. I thought of running 2 foreach loops, the first one selecting an object and the second one comparing it to every other but it ends up comparing itself with itself. Thanks for any info. Cheers

Share this post


Link to post
Share on other sites
Alternatively:


void Compare(IList list)
{
for( int i = 0; i < list.Count; ++i )
{
for( int j = i + 1; j < list.Count; ++j )
{
CompareListItem(list[i], list[j]);
}
}
}

void CompareListItem(object listItem1, object listItem2)
{
// do comparison stuff
}




This will cut out on comparisons against the same object and against objects that have already been compared. Kaze's example will work but there's be two comparisons of a lot of objects:

CompareObject(1, 2);
CompareObject(1, 3);
CompareObject(1, 4);
...
CompareObject(2, 1);
...
CompareObject(3, 1);
...
CompareObject(4, 1);
...
etc

Also, if you're using .NET 2.0 I'd recommend using the Systems.Collections.Generics.List<T> rather than just a standard System.Collections.List.

Share this post


Link to post
Share on other sites

This topic is 3725 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this