2016-12-05 55 views
2

如何將下面的循環轉換爲簡單的linq代碼。該程序正在篩選出重複的記錄。您可以看到SyID和PtID的組合在列表中重複出現,這些記錄在已過濾的列表中應該只有一個條目。首先,我們需要按SyID對這些項目進行分組,然後從列表中獲取不同的PtID。如何使用linq過濾不同的數據

public class ConnectionDetail 
{ 
    public long SyID { get; set; } 

    public long PtID { get; set; } 

    public double Usage { get; set; } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     var details = new List<ConnectionDetail>(); 
     details.Add(new ConnectionDetail() { SyID = 1, PtID = 1, Usage = 1500 }); 
     details.Add(new ConnectionDetail() { SyID = 1, PtID = 1, Usage = 1500 }); 
     details.Add(new ConnectionDetail() { SyID = 1, PtID = 2, Usage = 560 }); 
     details.Add(new ConnectionDetail() { SyID = 1, PtID = 3, Usage = 850 }); 
     details.Add(new ConnectionDetail() { SyID = 1, PtID = 4, Usage = 1222 }); 
     details.Add(new ConnectionDetail() { SyID = 1, PtID = 5, Usage = 2000 }); 
     details.Add(new ConnectionDetail() { SyID = 1, PtID = 5, Usage = 2000 }); 

     details.Add(new ConnectionDetail() { SyID = 2, PtID = 1, Usage = 1500 }); 
     details.Add(new ConnectionDetail() { SyID = 2, PtID = 2, Usage = 1300 }); 
     details.Add(new ConnectionDetail() { SyID = 2, PtID = 3, Usage = 560 }); 
     details.Add(new ConnectionDetail() { SyID = 2, PtID = 3, Usage = 560 }); 
     details.Add(new ConnectionDetail() { SyID = 2, PtID = 4, Usage = 1580 }); 
     details.Add(new ConnectionDetail() { SyID = 2, PtID = 4, Usage = 1580 }); 
     details.Add(new ConnectionDetail() { SyID = 2, PtID = 5, Usage = 4000 }); 

     var distinctSet = new List<ConnectionDetail>(); 
     foreach (var detail in details) 
     { 
      if (!distinctSet.Any(x => x.SyID == detail.SyID && x.PtID == detail.PtID)) 
      { 
       distinctSet.Add(new ConnectionDetail() { SyID = detail.SyID, PtID = detail.PtID, Usage = detail.Usage }); 
      } 
     } 
     Console.ReadKey(); 
    } 
+0

你可以用'.Distinct()'。這將返回一個具有不同值的IEnumerable。不過你必須重寫'.Equals()'和'.GetHashCode()'。 – RandomStranger

+0

可能的重複[由linq類的不同屬性](http://stackoverflow.com/questions/2537823/distinct-by-property-of-class-by-linq) – haim770

+0

爲什麼'用法'的類型是'雙',而不是'int'(或'long')? –

回答

6

使用EqualityCompare:

public class ConnectionDetailEqualityComparer : IEqualityComparer<ConnectionDetail> 
{ 
    public bool Equals(ConnectionDetail x, ConnectionDetail y) 
    { 
     return x.SyID == y.SyID && x.PtID == y.PtID && x.Usage == y.Usage; 
    } 

    public int GetHashCode(ConnectionDetail obj) 
    { 
     return obj.SyID.GetHashCode()^obj.PtID.GetHashCode()^obj.Usage.GetHashCode(); 
    } 
} 

有了它,你可以不同您的收藏:

var distinctSet = details.Distinct(new ConnectionDetailEqualityComparer());