1

I've got a problem. I have a list of objects (vehicle).

List<Vehicle> vehicleList = Vehicle.GetVehiclesFromDatabase();

And now I want something like this:

vehicleList.Remove(where vehicleList.Brand == "Volkswagen");

I hope I could explain what my problem is.

Many thanks in advance!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Possible duplicate of [c# remove item from list](http://stackoverflow.com/questions/10018957/c-sharp-remove-item-from-list) – raidensan Apr 21 '16 at 09:39
  • Try something like this : List results = vehicleList.Where(x => vehicleList.Brand != "Volkswagen").ToList(); – jdweng Apr 21 '16 at 09:40
  • Use `vehicleList.RemoveAll(item => item.Brand == "Volkswagen");` to remove all items with Volkswagen brand. To remove a single item you need to either pass the item, or know its index. – raidensan Apr 21 '16 at 09:41

3 Answers3

3

You can use List<T>.RemoveAll:

int recordsRemoved = vehicleList.RemoveAll(v => v.Brand == "Volkswagen");

The method takes a Predicate<T> (= Func<T,bool>), which will remove all items for which the predicate returns true.

For you this is equal to the following method:

bool Filter(Vehicle vehicle)
{
   return vehicle.Brand == "Volkswagen";
}
Alexander Derck
  • 13,818
  • 5
  • 54
  • 76
2

You can use linq to do this, like so

vehicleList = vehicleList.Where(v => v.Brand != "Volkswagen").ToList();

You can also do this with a RemoveAll

vehicleList.RemoveAll(v => v.Brand == "Volkswagen");
Alfie Goodacre
  • 2,753
  • 1
  • 13
  • 26
1

You can do like this

var itemToRemove = vehicleList.Single(r => r.Brand ==  "Volkswagen");
resultList.Remove(itemToRemove);

When you are not sure the item really exists you can use SingleOrDefault. SingleOrDefault will return null if there is no item (Single will throw an exception when it can't find the item). Both will throw when there is a duplicate value (two items with the same id).

var itemToRemove = vehicleList.SingleOrDefault(r => r.Brand ==  "Volkswagen");
if (itemToRemove != null)
    resultList.Remove(itemToRemove);
Vikram Bose
  • 3,197
  • 2
  • 16
  • 33