troubleshooting Question

Linq to select all pairs from a list

Avatar of deleyd
deleydFlag for United States of America asked on
C#LINQ Query
12 Comments1 Solution330 ViewsLast Modified:
I'm looking for a C# LINQ statement that will return all pairs from a list.

I've seen solution of the form:
var combinations = from item1 in list
                   from item2 in list
                   where item1 < item2
                   select Tuple.Create(item1, item2);
My problem is the (item1 < item2). What if these are objects that can't be compared?

The non-Linq solution would be something like:
for (int I=0; I < list.Count; ++I)
    for (int j = I+1; j < list.Count; ++j)
        pairs.Add(new Pair(list[I], list[j]);

So if list = {a,b,c,d,e}
the pairs would be:

(An item is not paired with itself)
And we don't want both {a,e} and {e,a}. Just the first one.
Eduard Ghergu
Architect - Coder - Mentor

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 12 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 12 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros