LINQ可以用于查找在排序列表差距? [英] Can LINQ be used to find gaps in a sorted list?
本文介绍了LINQ可以用于查找在排序列表差距?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有可能对我来说,使用LINQ的方式,让我确定9 是在排序列表中的第一个丢失值,而无需使用一个for循环和比较每个值到一个相邻的呢?
VAR listStringVals =新的[] {7,13,8,12,10,11,14};
//排序列表至7,8,10,11,12,13,14
VAR排序列表= listStringVals.OrderBy(C => int.Parse(三))了ToList()。
//这里需要一些魔术取得排序列表中的第一个缺口
解决方案
让
VAR串=新的String [] {7,13,8,12,10,11,14};
然后
VAR列表= Array.ConvertAll(字符串,S => Int32.Parse(S))排序依据(I = I标记)。
// 要么
变种列表= strings.Select。(S => int.Parse(多个))的OrderBy(ⅰ= I标记);
// 要么
变种列表= strings.OrderBy(S => int.Parse(多个));
(注意:<一href="http://stackoverflow.com/questions/1297231/convert-string-to-int-in-one-string-of-$c$c-using-linq">this问题)
然后
VAR的结果= Enumerable.Range(list.Min(),list.Count)。除(列表)。首先(); // 9
// 要么
INT分钟= list.Min(),最大值= list.Max();
VAR的结果= Enumerable.Range(最小,最大 - 最小+ 1)。除(列表)。首先();
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 value to the one adjacent to it?
var listStringVals = new [] { "7", "13", "8", "12", "10", "11", "14" };
// sort list to "7","8","10","11","12","13","14"
var sortedList = listStringVals.OrderBy(c => int.Parse(c)).ToList();
// need some magic here to get the first gap in the sorted list
解决方案
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();
这篇关于LINQ可以用于查找在排序列表差距?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文