2013-03-26 95 views
0

我有一個問題,除去2列表刪除重複的對象後,比較表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) 
} 

我想只得到1結果pumpsNonActive(結果=泵2)重複的對象。任何人都可以幫助我:/

+2

你'Pump'類具有覆蓋'Equals'和'GetHashCode'方法。 – MarcinJuraszek 2013-03-26 11:16:02

+0

您的存儲庫如何實現?你如何管理DbContext? – 2013-03-26 11:20:35

回答

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"}, 
}; 
+0

感謝@Habib的工作! :) 我改變它是這樣的: List lists = pumps.Where(p => activePumps.All(ap => ap.PumpID!= p.PumpID))。ToList(); – yovierayz 2013-03-26 11:29:44

+0

@yovierayz,也會工作 – Habib 2013-03-26 11:30:24

+0

@yovierayz,不客氣 – Habib 2013-03-26 11:30:59

0

Imeplement

public class Pump: IEquatable<Pump> 
{ 
    public bool Equals(Pump other) 
    { 
      ... 
    } 
} 
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(); 
    } 
} 
+0

感謝它的作品:) 實現:var lists = pumps.Where(p =>!activePumps.All(p.Equals))。ToList(); – yovierayz 2013-03-26 11:39:54