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

Started by
1 comment, last by Never 16 years, 6 months ago
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
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}
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.
-- All outta gum

This topic is closed to new replies.

Advertisement