0

鉴于以下示例,我将如何clientList在第二个示例中包含 5 个客户端?

我希望该list.Contains()方法仅检查FNameandLName字符串并在检查相等性时忽略年龄。

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
4

4 回答 4

2

创建一个实现 IEqualityComparer 的类,并在 list.contains 方法中传递对象

于 2013-02-28T11:03:02.477 回答
1
public class Client : IEquatable<Client>
{
  public string PropertyToCompare;
  public bool Equals(Client other)
  {
    return other.PropertyToCompare == this.PropertyToCompare;
  }
}
于 2013-02-28T11:04:31.533 回答
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();
    }
}

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

阅读此问题以了解为什么您还应该覆盖GetHashCode().

于 2013-02-28T11:22:30.973 回答
0

假设您使用的是 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);
    }
}
于 2013-02-28T11:18:21.940 回答