We help IT Professionals succeed at work.
Get Started

Linq to select all pairs from a list

deleyd
deleyd asked
on
292 Views
Last Modified: 2019-12-03
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);

Open in new window

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]);

Open in new window


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

(An item is not paired with itself)
And we don't want both {a,e} and {e,a}. Just the first one.
Comment
Watch Question
Architect - Coder - Mentor
CERTIFIED EXPERT
Commented:
This problem has been solved!
Unlock 1 Answer and 12 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant

An Experts Exchange subscription includes unlimited access to online courses.

Get Started
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE