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

我有一个 List allCars,我想从列表中删除第二个列表 List selectedCars 中的所有项目。我怎样才能用 LINQ 做到这一点?

我尝试了类似于:

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

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

4

2 回答 2

7

LINQ 代表语言集成查询。是用来查询的。从列表中删除项目不是查询。获取您要删除的所有项目是一个查询,或者获取所有不应删除的项目是另一个查询(这就是您拥有的那个)。

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

var itemsToRemove = new HashSet<Car>(selectedCars); //use a set that can be efficiently searched
allCars.RemoveAll(car => itemsToRemove.Contains(car));
于 2013-10-01T19:40:33.483 回答
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);
于 2013-10-01T19:48:54.513 回答