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

后端 未结 7 1178
攒了一身酷
攒了一身酷 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:28

    Let

    var strings = new string[] { "7", "13", "8", "12", "10", "11", "14" };
    

    Then

    var list = Array.ConvertAll(strings, s => Int32.Parse(s)).OrderBy(i => i);
    // or
    var list = strings.Select(s => int.Parse(s)).OrderBy(i => i);
    // or
    var list = strings.OrderBy(s => int.Parse(s));
    

    (note this question)

    and then

    var result = Enumerable.Range(list.Min(), list.Count).Except(list).First(); // 9
    // or
    int min = list.Min(), max = list.Max();
    var result = Enumerable.Range(min, max - min + 1).Except(list).First();
    
    0 讨论(0)
提交回复
热议问题