2

ok, let say i want to update multiple rows in database at once, without looping, if we do it with loop, it might look like this :

var products = (from prod in context.Products
               where prod.ProductCategoryID == myProductID
               select prod).ToList();


// modify each object
foreach (var product in products)
{
    product.PhoneNumber = ???;
    product.Name = ???;
    product.Address = ???;
}


context.SubmitChanges();

is there better way to do this? without doing any loop? consider me as a beginner on linq, so if there is some better way, it would be great if you provide me some example, thanks in advance.

NomNomNom
  • 811
  • 3
  • 12
  • 37
  • Parallel.For may be what your looking for - http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel.for.aspx and http://msdn.microsoft.com/en-us/library/dd460713.aspx – Sayse May 21 '13 at 07:04
  • Habib provides the answer. The only improvement I see is removing the ToList but that is off topic. – Pleun May 22 '13 at 19:19
  • is n't everyone free to give their opinion? to help other have a better understanding, i wonder. – NomNomNom May 23 '13 at 05:44

2 Answers2

2

LINQ is for quering records. Your current foreach loop is more readable and if you try other approach then it will use loop internally.

You can see this answer which modifies the collection using LINQ, but it is not the recommended way.

Community
  • 1
  • 1
Habib
  • 219,104
  • 29
  • 407
  • 436
0

You can use that line:

var products = (from prod in context.Products
                where prod.ProductCategoryID == myProductID
                select new Product(prod.PhoneNumber.ToLower(), prod.Name.ToUpper(), prod.Address.Trim()).ToList();

If you wanna change your products directly in your context object : make a specific function in Products class only. It will simply well designed.

 (from prod in context.Products
  where prod.ProductCategoryID == myProductID
  select prod.MakeChange(myPhoneNumber, myName, myAddress);

As you can call that line of code, prod should be changed along the LINQ query.

user1587368
  • 314
  • 2
  • 6