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.
C#LINQ Query
Last Comment
Eduard Ghergu
8/22/2022 - Mon
Eduard Ghergu
Hi,
You can create a function like Compare or something that can be used in the where clause:
where Compare(item1, item2)
deleyd
ASKER
If the list is ordered, is there a way to leverage the order of the list? Some way of converting the for loops using indexes, where it's easy to compare indexes, into a Linq statement?
Eduard Ghergu
Hi,
If the list is ordered, is there a way to leverage the order of the list?
I don’t understand the question.
In a list, the item index is just a way to get access to it.
If you want, you can use an OrderedCollection or OrderedDictionary
Hi,
In the end, what is i and what is j?
If you’ll start with
var combinations = from item1 in list
from item2 in list;
You be able to add any conditions do you want and select whatever you want.
deleyd
ASKER
How about can I wedge in the .Distinct() qualifier so there are no duplicates?
var combinations = from item1 in list from item2 in list where item1 != item2 select Tuple.Create(item1, item2);var pairs = conbinations.Distinct();
OK so I have to put parentheses around it all and then append a .Distinct()
Is Linq smart enough to do this in an efficient manner? Or does it create list.Count() squared items and then filter out the duplicates?
Actually it's looking like it's not too much of a hit if it creates all the possible combinations and then just weeds out the duplicates, so thank you this is the answer I was looking for.
Oh is there a way to get the Distinct without using the dot format?
You can create a function like Compare or something that can be used in the where clause:
where Compare(item1, item2)