Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient list self compare in LINQ?

Tags:

c#

linq

This may be very similar to this question but I would like to know the most efficient way in C# and LINQ to compare a list of elements to each other in the same list.

For example, in pseudo code I would like to do this:

foreach(i in list)    
    foreach(j in list.Except(i))    
        Compare(j,i)

I know that Except takes an enumerable instead of single item and may not be the best idea, but it should illustrate my intent.

Any ideas?

Update:

I guess this question was a bit to vague. The goal was to iterate over an list twice (using LINQ) while skipping over the pair (i, i); whatever Compare(i,j) actually does is irrelevant to my question.

There's two cases then, one where (i,j) == (j,i) and (i,j) != (j,i). For the former, George Duckett's skipwhile solution below does the trick, but what about the latter? This is where my original use of Except came in so that both (i,j) and (j,i) would be evaluated.

So to clarify, is there a better way to skip over an element in a list, other than list.Except(Enumerable.Repeat(i,1))?

like image 470
E.Beach Avatar asked Nov 16 '11 16:11

E.Beach


1 Answers

This will give you all pairs, assuming the order of pairs doesn't matter (Compare(i, j) == Compare(j, i)):

var test = from i in list
           from j in list.SkipWhile(j => j != i)
           where i != j // Remove the self-comparison if you want to
           select Compare(i, j);
like image 85
George Duckett Avatar answered Sep 23 '22 23:09

George Duckett