LINQ可以用于查找在排序列表差距?差距、列表、LINQ

由网友(你的专属味道)分享简介:是否有可能对我来说,使用LINQ的方式,让我确定9是在排序列表中的第一个丢失值,而无需使用一个for循环和比较每个值到一个相邻的呢?VAR listStringVals =新的[] {7,13,8,12,10,11,14};//排序列表至7,8,10,11,12,13,14VAR排序列表= listStringVa...

是否有可能对我来说,使用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};
 
.net中查询表达式 LINQ 简介

然后

  VAR列表= Array.ConvertAll(字符串,S => Int32.Parse(S))排序依据(I = I标记)。
// 要么
变种列表= strings.Select。(S => int.Parse(多个))的OrderBy(ⅰ= I标记);
// 要么
变种列表= strings.OrderBy(S => int.Parse(多个));
 

(注意: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();

阅读全文

相关推荐

最新文章