LINQ基于另一个对象列表从对象列表中删除对象

时间:2013-10-01 19:38:02

标签: c# linq

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

我有一个列表allCars,我想从列表中删除第二个列表中列出selectedCars的所有项目。如何使用LINQ完成此操作?

我尝试了类似的东西:

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

但是,它不会从allCars列表中删除任何项目。

2 个答案:

答案 0 :(得分:7)

LINQ代表Language INtegrated Query。它用于查询。从列表中删除项目不是查询。获取要删除的所有项目是查询,或者获取不应删除的所有项目是另一个查询(这是您拥有的项目)。

要从列表中删除项目,不应使用LINQ,您应该使用它提供的相应List工具来改变自身,例如RemoveAll

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

答案 1 :(得分:1)

示例解决方案代码

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