I have a list of variables which I need to convert to LIKE statements in SQL. The final query should look like the following:
...
WHERE ([TraceableItem].[IdentificationNo] LIKE N'%015558'
OR [TraceableItem].[IdentificationNo] LIKE N'%123456'
OR [TraceableItem].[IdentificationNo] LIKE N'%654321')
...
Below is my code to do it, but I feel it is fairly inefficient / redundant. Especially features like having a bool for firstLoop, and constantly checking for items already existing. I would be very grateful for a code review and tips on how to improve - I'm fairly rusty on C#
string queryInsertString = "([TraceableItem].[IdentificationNo] LIKE ";
string lastBatchNo = batchnos.Last();
List<string> alreadyAdded = new List<string>();
bool firstLoop = true;
foreach(string item in batchnos)
{
string splitItem = item.Split('/')[1];
if (!alreadyAdded.Contains(item)){
if (!firstLoop)
{
queryInsertString += " OR [TraceableItem].[IdentificationNo] LIKE N'%" + splitItem + "'";
} else
{
queryInsertString += "N'%" + splitItem + "'";
firstLoop = false;
}
alreadyAdded.Add(item);
}
}
batchnos
in this question). \$\endgroup\$