Can LINQ be used to find gaps in a sorted list?

后端 未结 7 1207
攒了一身酷
攒了一身酷 2020-12-13 04:22

Is it possible for me to use LINQ in a way that allows me to determine that \"9\" is the first missing value in the sorted list without using a for-loop and comparing each

7条回答
  •  猫巷女王i
    2020-12-13 05:14

    Why not just use All since all of the members in the collection need to conform to the criteria...

    Example

    someVar.All(v => someVar.Contains(v + 1) || v == someVar.Last())

    Then you don't have to order and its nicer.

    You could sort after this step or even during if you needed to but I personally would just use the sorted collection and have it do that work for me.

    You would grab the values if you needed to after doing the check then return the result of the check or hide it if you wanted to for some reason via a multi-line modification above along with a list to store the values in.

    e.g.

    someVar.All((v) => { 
        bool result = someVar.Contains(v + 1) || v == someVar.Last();
        if(!result) someList.Add(v);
        return true;
    });
    

    Checking the count of the list (which could be ordered) for a non zero value to indicate if it satisfied or not.

提交回复
热议问题