2013-02-28 57 views
0

鑑於下面的例子,我如何在第二個例子中使clientList包含5個客戶端?如何實現平等方法?

我想list.Contains()方法只檢查FNameLName字符串,並在檢查平等時忽略年齡。

struct client 
{ 
    public string FName{get;set;} 
    public string LName{get;set;} 
    public int age{get;set;} 
} 

實施例1:

List<client> clientList = new List<client>(); 

for (int i = 0; i < 5; i++) 
{ 
    client c = new client(); 
    c.FName = "John"; 
    c.LName = "Smith"; 
    c.age = 10; 

    if (!clientList.Contains(c)) 
    { 
     clientList.Add(c); 
    } 
} 

//clientList.Count(); = 1 

實施例2:

List<client> clientList = new List<client>(); 

for (int i = 0; i < 5; i++) 
{ 
    client c = new client(); 
    c.FName = "John"; 
    c.LName = "Smith"; 
    c.age = i; 

    if (!clientList.Contains(c)) 
    { 
     clientList.Add(c); 
    } 
} 

//clientList.Count(); = 5 
+0

你說你想忽視年齡,但是你的兩個例子意味着年齡確實被考慮在內。否則,id期望這兩個示例在列表中產生1個元素 – Jamiec 2013-02-28 11:03:14

+0

@Jamiec是的,但我希望在第二個示例中不考慮它。 – zaza 2013-02-28 11:14:42

回答

1
public class Client : IEquatable<Client> 
{ 
    public string PropertyToCompare; 
    public bool Equals(Client other) 
    { 
    return other.PropertyToCompare == this.PropertyToCompare; 
    } 
} 
+0

,我也可以在結構上實現接口,所以更好:) – zaza 2013-02-28 11:22:38

2

創建它實現的IEqualityComparer一類,並通過在對象方法list.contains

+0

沒有可以採用IEqualityComparer的List.Contains方法版本 - 該方法是LINQ to Objects的一部分,並且是在IEnumerable上聲明的擴展方法 MarcinJuraszek 2013-02-28 11:04:35

+0

@Saurabh由於MarcinJurazek提到,IEqualityComparer不適用於LINQ – zaza 2013-02-28 11:21:47

0

假設你正在使用C#3.0或grea之三,嘗試這樣的事情:

(下面的代碼沒有進行測試,但應該差不多右)

List<client> clientList = new List<client>(); 

for (int i = 0; i < 5; i++) 
{ 
    client c = new client(); 
    c.FName = "John"; 
    c.FName = "Smith"; 
    c.age = i; 

    var b = (from cl in clientList 
      where cl.FName = c.FName && 
        cl.LName = c.LName 
      select cl).ToList().Count() <= 0; 

    if (b) 
    { 
     clientList.Add(c); 
    } 
} 
1

覆蓋EqualsGetHashCode在你的結構:

struct client 
{ 
    public string FName { get; set; } 
    public string LName { get; set; } 
    public int age { get; set; } 

    public override bool Equals(object obj) 
    { 
     if (obj == null || !(obj is client)) 
      return false; 
     client c = (client)obj; 

     return 
      (string.Compare(FName, c.FName) == 0) && 
      (string.Compare(LName, c.LName) == 0); 
    } 

    public override int GetHashCode() 
    { 
     if (FName == null) 
     { 
      if (LName == null) 
       return 0; 
      else 
       return LName.GetHashCode(); 
     } 
     else if (LName == null) 
      return FName.GetHashCode(); 
     else 
      return FName.GetHashCode()^LName.GetHashCode(); 
    } 
} 

此實現處理所有的邊緣情況。

閱讀this question知道爲什麼你也應該覆蓋GetHashCode()