views:

48

answers:

3

I am returning two lists from the database using LINQ to SQL compiled query.

While looping the first list I remove duplicates from the second list as I dont want to process already existing objects again.

eg.

//oldCustomers is a List<Customer> returned by my Compiled Linq to SQL Statmenet that I have added a .ToList() at the end to

//Same goes for newCustomers

for (Customer oC in oldCustomers)
{
   //Do some processing
   newCustomers.Remove(newCusomters.Find(nC=> nC.CustomerID == oC.CusomterID));

}

for (Cusomter nC in newCustomers)
{
     //Do some processing
}


DataContext.SubmitChanges()

I expect this to only save the changes that have been made to the customers in my processing and not Remove or Delete any of my customers from the database.

Correct?

I have tried it and it works fine - but I am trying to know if there is any rare case it might actually get removed

+2  A: 

Right. When you call .ToList() extension method on any IEnumerable, a new in-memory list of such items is created, without any binding to the previous location of items.

You can add or remove items to/from such a list without fear of some side-effects.

But I have to add that your code is terrible performance-wise. for (Cusomter nC in newCusomters.Except(oldCustomers)) is much faster and easier to write.

Rotsor
A: 

Right. List<T>.Remove() removes the item from the List collection.

You need to call DeleteOnSubmit() on the LINQ Table class inorder to delete the item from your Database.

As an aside, your duplicate list item algorithm is pretty inefficient. One way to rewrite it, is to use the HashSet class in .NET 3.5 which will give you O(1) lookups instead of the O(n) that Find does.

Alan
A: 

I'm not sure what the point of re-inventing the wheel when it comes to unions. If you're using .NET 3.5 or later just use the LINQ union method.

Be sure to have:

'using System.Linq'

Then use:

var customers = oldCustomers.Union(newCustomers).To.List();

Union combines the two lists and removes any duplicates.

Note: The .ToList() is not necessary if you use var, it is necessary if you don't.

Evan Plaice