我有一个可以通过迭代解决的问题(如图所示),但是我认为必须有一种查询数据库并获得相同结果的方法?
short id;
if (someBoolean)
{
id = 99;
while (id > 0)
{
if (!db.MY_TABLEs.Any(x => x.ID == id))
break;
id--;
}
}
else
{
id = 1;
while (id < 100)
{
if (!db.MY_TABLEs.Any(x => x.ID == id))
break;
id++;
}
}
[基本上,我有一个充满整数的表,从0开始到100结束。在某处的数据中存在间隙,可能是24-58或35-93,依此类推。基于boolean
值,我需要确定间隙的起点或间隙的终点。
样本数据
{ 0, 1, 2, 98, 99, 100 }
// Start of gap, returns 3
// End of gap, returns 97
您可以使用Enumerable.Range
和Except
获得所需的结果
//Input array { 0, 1, 2, 98, 99, 100 };
var array = db.MyTables.Select(x => x.Id).ToList();
//Get the first and last elements
int a = array.OrderBy(x => x).First();
int b = array.OrderBy(x => x).Last();
//Fill the complete list
var completelist = Enumerable.Range(a, b - a + 1).ToList();
//Filter the missing list
var missingfromlist = completelist.Except(array).ToList();
//Read first and last element from missing list
Console.WriteLine($"Start of gap: { missingfromlist.First()}, End of gap : { missingfromlist.Last()}");
输出
Start of gap: 3, End of gap : 97
您可以这样做:
var range = Enumerable.Range(0, 99);
var missingIds = db.MyTables.Where(x => !range.Contains( x.Id)).Select(s => s.Id);
这写了一个非常讨厌的选择语句,例如:
select Id from MyTable where Id not in (0, 1, 2, 3, 4 ...)
然后您将拥有所有确切的缺失数据,可以在此处进行排序,以根据需要获取缺口的起点和终点。