Search code examples
linqigrouping

Check if IGrouping value contains result


I have an IGrouping structure

IGrouping<TierRequest,PingtreeNode>

PingtreeNode contains a property of Response which in turn has a property Result.

    public class PingtreeNode
    {
        public ResponseAdapter Response { get; set;}
        // ... more properties
    }

    public class ResponseAdapter
    {
        public int Result { get; set; }
        // ... more properties
    }

What I want to do is check whether PingtreeNode contains any nodes with a Result == 2. I know the answer includes a SelectMany but I'm struggling to get the correct syntax.

Anyone help?


Solution

  • Because you have to check

    whether PingtreeNode contains any nodes with a Result == 2

    I would use Any method:

    IGrouping<TierRequest,PingtreeNode> source;
    
    bool anyResultIs2 = source.SelectMany(x => x)
                              .Any(x => x.Response.Result == 2);
    

    It can also be done without SelectMany:

    bool anyResultId2 = source.Any(g => g.Any(x => x.Response.Result == 2));
    

    And because both SelectMany and Any are lazy (return only one element at the time and end execution as soon as result is determined), performance of both approaches should be similar.