2

i have a query like below and i want to update all elements of sequence. but without using foreach/for

var res = _context.tbl1.Where(/* Conditions here */);
res.//Using a method to performing changes;
2
  • And how do you think that will work, if you dont go through every element? Commented Jul 22, 2010 at 11:33
  • hm... i think should be exist an Extension Method to do this, otherwise why we can iterate each element using Where? Commented Jul 22, 2010 at 11:37

4 Answers 4

2

If you're asking whether you can do set based updates in linq-to-sql as you can in sql, i'm afraid you can't. You either have to individually update each l2s object and call SubmitChanges() when you're done, or call ExecuteCommand() with your sql query.

Here's a thread you might be interested in - http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/0f014318-5259-43c7-8518-06948cec465e

Edit: Actually, this may be of interest to you - Updating multiple rows Linq vs SQL

If you have a look there's a link to here - http://www.aneyfamily.com/terryandann/post/2008/04/Batch-Updates-and-Deletes-with-LINQ-to-SQL.aspx which looks kinda cool. Might have to check it out myself!

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, so i can't do that and also thanks for provided links. I got the answer
2

Write an extension method for it

public static class IEnumerableExtensions
{
    public static void ForEach<T>(this IEnumerable<T> seq, Action<T> action)
    {
        foreach (var item in seq)
        {
            action(item);
        }
    }
}

But note that under the hood you're still looping through - just like the Where extension method and all the others. The extension methods hide the looping.

Comments

1

You could write an extension method for IEnumerable<T> that did iterate and perform the action you required, potentially using a delegate or Func to make it more generic.

Comments

0

Are you looking for Select?

1 Comment

In that case, see Frank's answer. LINQ by default can only be used to select data, not update it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.