Iterate every combination of two elements in HashSet
.net, c#, hashset, linq
Solution
There is no built-in method to do this in C#. Since `HashSet<T>` is not indexed *, you cannot do it with two loops either.
If this is a one-time deal, the simplest solution is to make two nested loops on the results of `ToList()` or `ToArray()`, like this:
var items = hashSet.ToList();
for (var i = 0 ; i != items.Count ; i++) {
var a = items[i];
for (var j = i+1 ; j != items.Count ; j++) {
var b = items[i];
}
}
If you are looking for something reusable, make an extension method on `IEnumerable<T>` that produces all pairs:
static IEnumerable<Tuple<T,T>> MakeAllPairs<T>(this IEnumerable<T> data) {
var items = data.ToList();
for (var i = 0 ; i != items.Count ; i++) {
var a = items[i];
for (var j = i+1 ; j != items.Count ; j++) {
var b = items[i];
yield return Tuple.Create(a, b);
}
}
}
Now you can iterate your pairs in a single loop:
foreach (var pair in hashSet.MakeAllPairs()) {
Console.WriteLine("{0} {1}", pair.Item1, pair.Item2);
}
* Technically, you could use `ElementAt<T>(int)` extension from `Enumerable`, but that would be very slow on large sets.
Problem
How could I iterate through each combination of two elements in a HashSet once? ``` foreach (var elt1 in hashSet) { foreach (var elt2 in hashSet) { ... } } ``` This would iterate the combinations of two but would iterate each combination TWICE. I'd like to do it once. I think it's easy to do in Python. Is there any way to do it in C#? Sample: input hashSet: { 1, 2, 3, 4 } iterate through: (1,2), (1,3), (1,4), (2,3), (2,4), (3,4)