How do I get all possible pairs of items in a list (order not relevant)?
E.g. if I have
var list = { 1, 2, 3, 4 };
I would like to get these tuples:
var pairs = {
new Tuple(1, 2), new Tuple(1, 3), new Tuple(1, 4),
new Tuple(2, 3), new Tuple(2, 4)
new Tuple(3, 4)
}
Slight reformulation of cgeers answer to get you the tuples you want instead of arrays:
(Use
ToListorToArrayif you want.)In non-query-expression form (reordered somewhat):
Both of these will actually consider n2 values instead of n2/2 values, although they’ll end up with the correct answer. An alternative would be:
… but this uses
Skipwhich may also not be optimized. It probably doesn’t matter, to be honest – I’d pick whichever one is most appropriate for your usage.