简体   繁体   中英

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.

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));

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM