Can this loop be written more succinctly?

c#

Solution

You can try this code that moves the assignment into the invocation of `AreSimilar`:

QueueElement elemA, elemB
while (queueA.Count > 0 && AreSimilar(elemA = queueA.Peek(), elemB = queueB.Peek())) {
    Debug.Assert(elemA.SomeProperty == elemB.SomeProperty);
    queueA.Dequeue();
    queueB.Dequeue();
}

Note that this is not necessarily more readable. In fact, your version is pretty good in terms of readability. The only thing I would do is inverting the condition to decrease nesting, but I'd leave everything else in place:

while (queueA.Count > 0)
{
    var elemA = queueA.Peek();
    var elemB = queueB.Peek();
    if (!AreSimilar(elemA, elemB))
    {
        break;
    }
    Debug.Assert(elemA.SomeProperty == elemB.SomeProperty);
    queueA.Dequeue();
    queueB.Dequeue();
}

Problem

I have two queues, let's say A and B, on which I execute the following algorithm: ``` while (queueA.Count > 0) { var elemA = queueA.Peek(); var elemB = queueB.Peek(); if (AreSimilar(elemA, elemB)) { Debug.Assert(elemA.SomeProperty == elemB.SomeProperty); queueA.Dequeue(); queueB.Dequeue(); } else { break; } } ``` Something tells me this could be written more succinctly; Peek() and Dequeue() might be combined in one operation as Dequeue() returns the same element as Peek(), and the if statement might be fused with the while statement, avoiding an explicit break. I'm just not seeing how to preserve the same behavior exactly, i.e. I don't want to remove an element unless it satisfies the condition in the 'if'.

Original source