I need to compare a list of sequential integers created from a C# Windows Form to a database table of integers, indicating if there are duplicates.
I have a version that works, below, but I'm assuming it's probably the least efficient way of doing this - comparing the C# list one by one to each integer in the database table.
Should I get the integers from the database into C#, and then compare? Or is there a sql way of asking:
if any item in list A is contained in list B, etc.... without comparing each number one-by-one?
I've seen lots of opinions on just looking for 1 item in a database, but I need an efficient way of comparing C# lists of sometimes 5,000 or more to a database table that can end up having hundreds of thousands of records.
public static string VerifyManufacturingSerialOnly(int count, int beginning)
{
string duplicateSerials = "";
int currentSerial = beginning;
for (int i = 0; i < count; i++)
{
OleDbConnection connection = BadgeDatabaseDB.GetConnection();
string checkStatement
= "SELECT * "
+ "FROM SerialNumbersMFG "
+ "WHERE SerialNumber = @CurrentSerial";
OleDbCommand command =
new OleDbCommand(checkStatement, connection);
command.Parameters.AddWithValue("@CurrentSerial", currentSerial);
try
{
connection.Open();
OleDbDataReader dataReader =
command.ExecuteReader(CommandBehavior.SingleRow);
if (dataReader.Read())
{
duplicateSerials +=
"Serial # " +
currentSerial +
" already exists in order # " +
dataReader["OrderNumber"].ToString() + "\n";
}
else { }
}
catch (OleDbException ex)
{
throw ex;
}
finally
{
connection.Close();
}
currentSerial++;
i++;
}
return duplicateSerials;
Two ways:
SerialNumber FROM SerialNumbersMFG
and then you can use linq list1.Intersect(list2)
IN
clause, so you can use the query like: SELECTSerialNumber FROM SerialNumbersMFG WHERE SerialNumber IN (1,2,3...)
which will also do the required thing. Since you mention that the DB can have hundreds of thousand of record I would suggest that second way is better. Please use stringbuilder
for concatenation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.