繁体   English   中英

如何实现平等方法?

[英]How to implement a equality method?

给定以下示例,在第二个示例中,如何使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

创建一个实现IEqualityComparer的类,然后将对象传递到list.contains方法中

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

在您的结构中覆盖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();
    }
}

此实现处理所有边缘情况。

阅读此问题,以了解为什么还要覆盖GetHashCode()

假设您使用的是C#3.0或更高版本,请尝试如下操作:

(以下代码未经测试,但应该正确无误)

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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM