更新时间:2023-11-29 08:29:28
4年后可能关注的人:
To whom it may concern after 4 years:
因为您只对第一个缺失的密钥感兴趣,解决方案是:
Because you are only interested in the first missing key, the solution is:
int[] keys = { 1, 2, 3, 5, 7 };
var arrayWithFirstMissingKey = keys
.Select((key, index) => new { Key = key, Index = index })
.Where(tuple => (tuple.Index + 1 < keys.Length) && (keys[tuple.Index + 1] > tuple.Key +1))
.Select(tuple => tuple.Key +1)
.Take(1)
.ToArray();
第一个 选择创建(Key,Index)元组,因为Enumerables不支持索引,
The 1st Select creates (Key, Index) tuples, because Enumerables don't support indexes,
Where子句检测到与其后继有间隙的第一个密钥。
The Where clause detects the first key which has a gap to it's successor.
第二个选择确定缺口的第一个缺失密钥。
The 2nd select determines the first missing key of the gap.
在找到第一个缺失密钥后,Take子句可以防止不必要的开销。
The Take clause prevents unnecessary overhead after the first missing key is found.