简体   繁体   English

LINQ根据另一个对象列表从一个对象列表中删除对象

[英]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. 我有一个List allCars,我想从列表中删除第二个List selectedCars列表中的所有项目。 How can I accomplish this with LINQ? 如何使用LINQ完成此操作?

I tried something similiar to: 我尝试了类似的方法:

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

However it is not removing any items from the allCars list. 但是,它不会从allCars列表中删除任何项目。

LINQ stands for Language INtegrated Query. LINQ代表语言集成查询。 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 : 要从列表中删除您不应该使用LINQ的项目,您应该使用它提供的用于自身变异的适当的List工具,例如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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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