John Doe
John Doe

Reputation: 3233

LINQ to remove objects from a list of objects based on another list of objects

public class Car
{
    private string _manufacturer = string.empty;        
    private string _color = string.empty;
    private string _modelLine= string.empty;

    public string Manufacturer
    {
        get { return _manufacturer; }
        set { _manufacturer= value; }
    }
    public string Color
    {
        get { return _color; }
        set { _color= value; }
    }
    public string ModelLine
    {
        get { return _modelLine; }
        set { _modelLine= value; }
    }
}

I have a List allCars, and I want to remove from the list all items that are in a second list List selectedCars. How can I accomplish this with LINQ?

I tried something similiar to:

List<Car> listResults = allCars.Except(selectedCars).ToList();

However it is not removing any items from the allCars list.

Upvotes: 1

Views: 8286

Answers (2)

Hossain Muctadir
Hossain Muctadir

Reputation: 3626

Sample Solution Code

    var item = new Car { Color = "red", Manufacturer = "bmw", ModelLine = "3" };
    var car = new Car { Color = "red", Manufacturer = "toyo", ModelLine = "2" };
    var item1 = new Car { Color = "red", Manufacturer = "marc", ModelLine = "23" };

    var carsa = new List<Car>
        {
            item1,
            item,
            car
        };
    var carsb = new List<Car>
        {
            item,
            car
        };

    carsa.RemoveAll(carsb.Contains);

Upvotes: 1

Servy
Servy

Reputation: 203829

LINQ stands for Language INtegrated Query. It is for querying. Removing items from a list isn't querying. Getting all of the items that you want to remove is a query, or getting all of the items that shouldn't be removed is another query (that's the one that you have).

To remove items from the list you shouldn't use LINQ, you should use the appropriate List tools that it provides for mutating itself, such as RemoveAll:

var itemsToRemove = new HashSet<Car>(selectedCars); //use a set that can be efficiently searched
allCars.RemoveAll(car => itemsToRemove.Contains(car));

Upvotes: 7

Related Questions