Getting the previous sibling of a node using Roslyn I am currently creating an analyzer using the roslyn sdk. I ran into a case where it was simpler to check child tokens for Wait()/.Result.

The code i am sharing works perfectly fine - However i was unable to find a better way on google nor through browsing the docs.

This way of getting the previous sibling of a node feels very weird - Is there a better way?

        if (context.Node is IdentifierNameSyntax identifierName)
        {
            if (identifierName.Identifier.Text == TaskIdentifierWait || identifierName.Identifier.Text == TaskIdentifierResult)
            {
                var siblingsAndSelf = identifierName.Parent.ChildNodes().ToImmutableArray();
                var selfIndex = siblingsAndSelf.LastIndexOf(identifierName);
                if (selfIndex &lt;= 0)
                    return;

                var previousSibling = siblingsAndSelf[selfIndex-1];
You could iterate over the ChildNodes only once with the Zip extension where the first collection starts at the first element and the other one at the second element with Skip(1). This will produce tuples with pairs such as Previous &amp; Current. Now you can filter it and pick at the same time the Last element that satisfies the condition:

var childNodes = new[] { "a", "a", "b", "c", "a" };

var previousSibling =
    childNodes
        .Zip(childNodes.Skip(1), (p, c) =&gt; (Previous: p, Current: c))
        .Last(t =&gt; t.Current == "c").Previous; // b