alexchet
alexchet

Reputation: 479

Foreach delete with linq

The following statement should delete someCars from allCars, and it works, however I was wondering if there is a better solution which specifically uses only linq

foreach (var car in someCars) 
{
    db.allCars.DeleteObject(car); 
}

Note that db is the instance of the db entities.

Any help would be much appreciated.

Upvotes: 3

Views: 3458

Answers (3)

Shady
Shady

Reputation: 364

using Linq as ForEach:

db.allCars.Where(/* condition */).ToList().ForEach(car => db.allCars.Remove(car));

in the same line of this answer :) , How do I delete multiple rows in Entity Framework (without foreach)

Upvotes: 4

ruffen
ruffen

Reputation: 1721

You can use:

db.allCars.RemoveAll(db.allCars.Where(/* condition */));

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

You can use EntityFramework.Extended library to delete entities based on some condition (library available from Nuget):

db.allCars.Delete(car => /*condition*/);

Upvotes: 5

Related Questions