0

I am trying to save values to database from two lists by applying foreach loop on them but due to use of loop inside loop it is saving duplicate values to database which I don't want.Help me!

I am not able to find any solution so did not tried anything yet

var list1 = obj.getlists1();
var list2 = obj.getlists2();

foreach(var item in list1)
{
    foreach(var item1 in list2)
    {
         SqlConnection con = new SqlConnection(connectionstring);

         string sql = "INSERT INTO tbllogs (QBDID,PHPID,CreatedBy) values (" ' +item.QBDID+ " ' , " ' +item1.PHPID+ " ' , " ' + item.CreatedBy + " ')";

         con.Open();

         SqlCommand cmd = new SqlCommand(sql, con);
         cmd.ExecuteNonQuery();
    }
}

I want that the values that are already entered into database will not be able to enter into database i.e. I don't want any duplicate values from the loop to enter to database.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
jiga
  • 133
  • 10
  • 1
    [**SQL Injection alert**](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - you should **not** concatenate together your SQL statements - use **parametrized queries** instead to avoid SQL injection - check out [Little Bobby Tables](http://bobby-tables.com/) – marc_s Sep 08 '19 at 05:48
  • I want solution for my problem your answer does not solve my problem – jiga Sep 08 '19 at 07:11

2 Answers2

0

The following snippet can be used to merge the lists and get the distinct, thus unique elements:

var commonList = list1.Union(list2 ).Distinct();
MaartenDev
  • 5,631
  • 5
  • 21
  • 33
jiga
  • 133
  • 10
0

It's answered here by @Hadi: SQL Server INSERT INTO with WHERE clause

Add in front of your Insert statement

IF NOT EXISTS(Select 1 From tbllogs WHERE QBDID like 'item.QBDID')`

Check out the accepted answer. Should work.

EDIT: Of course you might need to check in the WHERE clause all your values.

KH S
  • 444
  • 1
  • 4
  • 8