tags:

views:

12

answers:

1

I have a table of Contacts, and a table of Groups which has a many-to-many relationship managed by a simple contacts_groups table:

contacts_groupsID Identity INT ContactID INT GroupID INT

I have a delimted String of contact IDs e.g. "1|23|987|2346|33|9821|" which I need to insert into the contacts_groups table (along with the groupID). I am using LinQ to SQL and C#, but want to know the most efficient way of looping through the delimited string (probably .Split()) checking for duplicates and inserting if not exist.

A: 
List<int> requested = contactIds.Split('|')
  .Select(s => int.Parse(s))
  .Distinct()
  .ToList();

List<int> existing = (
from x in db.GroupsContacts
where x.GroupId == groupId
select x.ContactId
).ToList();

List<int> toBeAdded = requested.Except(existing).ToList();

foreach(int id in toBeAdded)
{
  GroupsContacts record = new GroupsContacts();
  record.GroupID = groupID;
  record.ContactID = id;
  db.InsertOnSubmit(record);
}

db.SubmitChanges();
David B