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

后端 未结 7 1197
攒了一身酷
攒了一身酷 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条回答
  •  独厮守ぢ
    2020-12-13 05:20

    var listStringVals = new string[] {"7", "13", "8", "12", "10", "11", "14"};
    var sortedInts = listStringVals.Select(c => int.Parse(c)).OrderBy(x => x);
    var noGaps = Enumerable.Range(sortedInts.First(), 
                                  sortedInts.Last() - sortedInts.First() + 1);
    var missing = noGaps.Except(sortedInts).Select(x => x.ToString()).First();
    

    Edit: fixed range generation thanks to BeemerGuy's answer. Still leaving mine, as it doesn't ignore the ugliness of a list of string representations of ints :)

提交回复
热议问题