删除比较2列表后的重复对象

时间:2013-03-26 11:14:25

标签: c# linq

我在删除2个列表中的重复对象时遇到问题

public class Pump
{
    public int PumpID { get; set; }
    public string PumpName { get; set; }
    public string LogicalNumber { get; set; }
}

public void LoadPump()
{
    var pumps = _pumpRepository.GetAll(); // 2 Pump
    var pumpsActive = _pumpRepository.GetAllActive(); // 1 Pump Active (Pump 1)
    //i try like this
    List<Pump> pumpsNonActive = pumps.Except(pumpsActive).ToList(); // Result 2
    //if like this
    List<Pump> pumpsNonActive = pumpsActive.Except(pumps).ToList(); // Result 1 (Pump 1)
}

我想在pumpNonActive(结果=泵2)中只获得1个结果。任何人都可以帮助我:/

3 个答案:

答案 0 :(得分:1)

实施.Equals(object).GetHashCode()

public class Pump
{
    public int PumpID { get; set; }
    public string PumpName { get; set; }
    public string LogicalNumber { get; set; }

    public override bool Equals(object o)
    {
        var casted = o as Pump;
        if (casted == null)
            return false;

        return PumpID == o.PumpID;
    }

    public override int GetHashCode()
    {
        return PumpID.GetHashCode();
    }
}

答案 1 :(得分:1)

您可以覆盖Equals,也可以尝试以下操作:

 List<Pump> pumpsNonActive = pumps.Where(r => !pumpsActive
                                             .Any(t => t.PumpID == r.PumpID))
                                  .ToList();

这适用于以下数据集:

List<Pump> pumps = new List<Pump>()
{
    new Pump() { PumpID = 1, LogicalNumber = "SomeName", PumpName="PumpName1"},
    new Pump() {PumpID = 2, LogicalNumber = "Number", PumpName = "PumpName2"},
    new Pump(){PumpID = 3, LogicalNumber = "Number", PumpName = "PumpName3"},
};

List<Pump> pumpsActive= new List<Pump>()
{
    new Pump() { PumpID = 1, LogicalNumber = "2", PumpName="3"},
};

答案 2 :(得分:0)

Imeplement

public class Pump: IEquatable<Pump>
{
     public bool Equals(Pump other)
     {
          ...
     }
}