C# – Deleting rows in a table with Linq to SQL

asp.netc++linqsql

I have a sports database with a table groupmembers which have the fields ID, groupID and memberID. I get the memberID from a textbox called txtRemoveGroupMember and the groupID from a checkboxlist. Now I want to delete the rows which have both the groupID and the memberID.
I have tried this code:

foreach(ListItem listItem in cblRemoveMemberFromGroup.Items)
{
       int memberid = Convert.ToInt32(txtRemoveGroupMember.Text);
       int groupid = Convert.ToInt32(listItem.Value);

       var removeFromGroup = from gm in dataContext.GroupMembers
            where (gm.memberID == memberid) && (gm.groupID == groupid)
            select gm;

       dataContext.GroupMembers.DeleteOnSubmit(removeFromGroup);
       dataContext.SubmitChanges();
}

But I get this error:

Error 7 Argument 1: cannot convert from 'System.Linq.IQueryable<GSI_side.GroupMember>' to 'GSI_side.GroupMember'

And this error:

Error 6 The best overloaded method match for 'System.Data.Linq.Table<GSI_side.GroupMember>.DeleteOnSubmit(GSI_side.GroupMember)' has some invalid arguments

Hope someone can help me figure this out!

Best Solution

You have to call .ToList()

var items = removeFromGroup.ToList();
foreach (var item in items)
  dataContext.GroupMembers.DeleteOnSubmit(item);

For batch deletes I use this, because LINQ to SQL first loads the entire data which is going to be deleted, then it does the deletes each by each.

https://terryaney.wordpress.com/2008/04/14/batch-updates-and-deletes-with-linq-to-sql/

https://github.com/longday/LINQ-to-SQL-Batch-Updates-Deletes