使用Linq在列表中的列表中查找列表中已删除的项目

时间:2018-07-26 13:25:52

标签: c# .net linq

为简化我的问题,假设我有车库课:

class Garage
{
 List<Car> cars;
 string name; //unique for each garage
}

class Car
{
  string Name; //unique for each car
  ... other fields
}

现在,在卖掉一些旧车或购买了一些新车之后,我有一个原始清单List<Garage> oldGarages和一个类似清单List<Garage> newGarages,现在我想知道删除了哪些车以及它在哪个车库-> List<Garage> deletedCars;

使用Linq是否可以通过简单的方式实现?重要的是我要避免创建新的Car对象。

P.S。我想按唯一的汽车名称进行过滤,不能对汽车对象使用Equality或任何形式

没有linq,我可以这样做(这是伪代码,所以请不要注意细节,我在火车上:))

List<Garage> soldCars;

foreach (var oldGarage in oldGarages.ToList())
{
    soldCars.Add(oldGarage);  //assume the garage was sold

    var garage = newGarages.SingleOrDefault(g => g.Name == oldGarage.Name);
    if (garage == null) //this garage was sold as a whole
        continue;
    else
    {
        foreach (var oldCar in oldGarages.Cars.ToList()) //find out which cars was sold from this garage (if any)
        {
            var car = garage.Cars.SingleOrDefault(c => c.Name == oldCar.Name);
            if (car != null) //this car was not sold,remove it from the sold list
                oldGarage.Remove(car);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我认为这应该可以解决问题

public static void CarTest()
{
    var origList = new List<Car>();
    origList.Add(new Car() { Name = "A"});
    origList.Add(new Car() { Name = "B" });
    origList.Add(new Car() { Name = "C" });
    origList.Add(new Car() { Name = "D" });
    origList.Add(new Car() { Name = "E" });

    var afterList = origList.Where(c => c.Name != "A");

    var missingList = origList.Except(afterList);

}