查找给定范围内的数字缺失

因此,我的编码有问题,想知道是否有人可以帮助我。查找给定范围内的数字缺失

基本上我使用VB.NET和MSSQL在用户设置的给定范围之间查找缺少数字的程序。该程序将从表中读取并在文本框中输出结果。上面的代码到目前为止我可以想出。但问题是,我得到错误的输出,而不是我想要的。这是输出的image。

Function FindingMissingNumber() As String 

Dim intX As Integer = Nothing

Dim intY As Integer = Nothing

Dim strSting As String = Nothing

Dim strSqlQUery As String = Nothing

Dim cmdSqlCommand As Data.SqlClient.SqlCommand = Nothing

Dim rdrDataReader As Data.SqlClient.SqlDataReader = Nothing

'------------------------------------------------------------------------------------------------------------------------

'-> Process

'------------------------------------------------------------------------------------------------------------------------

strSqlQUery = "Select ExReportPolicyNo From DBReport Order by ExReportPolicyNo"

Dim msSqlConnection As New Data.SqlClient.SqlConnection()

'NOTE - You may need to CHECK your connection string!!! in the line below

msSqlConnection.ConnectionString = "Data Source=SISBSQL\SISBSQL;Initial Catalog=ExceptionReport;User ID=sa;Password=123;"

cmdSqlCommand = New Data.SqlClient.SqlCommand(strSqlQUery, msSqlConnection)

If cmdSqlCommand.Connection.State = Data.ConnectionState.Closed Then cmdSqlCommand.Connection.Open()

rdrDataReader = cmdSqlCommand.ExecuteReader()

If rdrDataReader.HasRows Then

Do While rdrDataReader.Read()

intX = txtRangeLeft.Text

intY = txtRangeRight.Text

'intY = rdrDataReader.GetValue(rdrDataReader.GetOrdinal("ExReportPolicyNo"))

Do While intX <> intY

intX = intX + 1

If intX <> intY Then

strSting = strSting & intX & ", " 'if it is not, then record the non sequential number into the string

Else

Exit Do

End If

Loop

Loop

End If

If cmdSqlCommand.Connection.State = Data.ConnectionState.Open Then cmdSqlCommand.Connection.Close()

'return string

Return strSting

'tidy up

intX = Nothing

intY = Nothing

strSting = Nothing

strSqlQUery = Nothing

cmdSqlCommand = Nothing

rdrDataReader = Nothing

End Function

正如你可以看到程序循环多次,并发出错误的输出。输出只能读取“286118,286120,286121”。问题是我出错了?

回答:

试试这个(使用LINQ)

更改查询开始和结束值

Select distinct ExReportPolicyNo From DBReport 

Where ExReportPolicyNo between @start and @end

Order by ExReportPolicyNo

从查询创建列表之间返回行:

Dim originalList as List(Of Integer) 

If rdrDataReader.HasRows Then

Do While rdrDataReader.Read()

originalList.Add(rdrDataReader.GetInt(0))

Loop

End If

从创建的范围列表你开始和结束号码

//Dim rangeList = Enumerable.Range(286117, 286121 - 286117 + 1).ToList() 

Dim starti = Int32.Parse(txtRangeLeft.Text)

Dim endi = Int32.Parse(txtRangeRight.Text)

Dim rangeList = Enumerable.Range(starti, endi - starti + 1).ToList()

找到所有失踪数字

Dim missingList = originalList.Except(rangelist) 

从列表上方的创建

strString = String.Join(",", missingList.Select(x => x.ToString()).ToArray()) 

以上是 查找给定范围内的数字缺失 的全部内容, 来源链接: utcz.com/qa/262099.html

回到顶部