Learning about data structures- when to use them, how to use them, and why- is a make-or-break moment for a lot of programmers. Some programmers master this. Some just get as far as hash maps and call it a day, and some… get inventive.

Let’s say, for example, that you’re Jim J’s coworker. You have an object called a `Closing`. A `Closing` links two `Entry`s. This link is directed, so entry `1->2` is one `Closing`, while `2->1` is another. In real-world practice, though, two `Closing`s that are linked together in both directions should generally be interacted with as pairs. So, `1->2` and `2->1` may not be the same object, but they’re clearly related.

Jim’s coworker wanted to gather all the pairs were together, and put them into groups, so `1->2` and `2->1` are one group, while `3->1` and `1->3` are another. This was their approach.

``````// go through all closings
// ordered by sum of entryId and refEntryId to get all pairs together
foreach (var closing in closings.OrderBy(c => c.EntryId + c.RefEntryId))
{
// exit condition for group
// if the sum of the entry ids is different then its another group
if (entryIdRefEntryId != closing.EntryId + closing.RefEntryId)
{
// get new sum
entryIdRefEntryId = closing.EntryId + closing.RefEntryId.Value;
// return and reset
if (closingGroup != null)
{
yield return closingGroup;
closingGroup = null;
}
}

// the rest of the logic omitted
}``````

Jim claims the “original comments preserved” here, though I suspect that `// the rest of the logic omitted` might not be an original comment. Then again, looking at the code, that might not be the case.

This sorts the closings by the sum of their entry IDs. For each `Closing` in that list, if the sum of its refs are the same, we add it to a `closingGroup` (that’s some of the omitted code). If the sum isn’t the same, well, we’ve reached the end of a group. Update our sum, and yield the current `closingGroup` back to the calling code.

For funsies, follow that chain of logic on pairs like: `11<->14`, `12<->13`, and `10<->15`.

Jim adds: “These pairings are not very probable, but still possible, and that makes the reproduction of the bug quite challenging.”