John Skeets answer to this question, Select all unique combinations of a single list, with no repeats, using LINQ, works awesomely.
However, can someone break down component by component the inner workings of how the first answer is working:
List<int> slotIds = new List<int> {1, 2, 3};
var query = slotIds.SelectMany((value, index) => slotIds.Skip(index + 1),
(first, second) => new { first, second });
It's roughly equivalent in concept to this, although the actual execution model is different of course (lazy etc):
for (int i = 0; i < slotIds.Count; i++)
{
int first = slotIds[i];
for (int j = i + 1; j < slotIds.Count; j++)
{
int second = slotIds[j];
results.Add(new { first, second });
}
}
The SelectMany
taking a projection from value
and index
is a way of using both first
and i
to make an inner loop. We need the index so that we can skip index + 1
values, which is equivalent to the j
loop starting at i + 1
in the above code.
Does that help? If not, could you pinpoint which bit is confusing?
EDIT: Aargh - I hadn't realized that the other question you were referring to started out with this code! I think it's still useful though, to give the paragraph below something to hang on...
If you understood the alternative (query expression) version of my answer, then the first version is similar, just using an overload of SelectMany
which allows you to use both the value and index in the "outer" sequence.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With