Jump to content
  • Advertisement
Sign in to follow this  
one mind

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

This topic is 3889 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
Advertisement


void Compare(List list){
foreach(Object a in list){
foreach(Object b in list){
if (a!=b){
CompareObject(a,b);
}
}
}
}

void CompareObject(Object a,Object b){
//do stuff here
}


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, 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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!