如何实现一个相等方法
本文关键字:一个 方法 实现 何实现 | 更新日期: 2023-09-27 18:01:28
给出下面的例子,我如何在第二个例子中使clientList
包含5个客户端?
我希望list.Contains()
方法只检查FName
和LName
字符串,并且在检查是否相等时忽略年龄。
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中传递对象。包含方法
public class Client : IEquatable<Client>
{
public string PropertyToCompare;
public bool Equals(Client other)
{
return other.PropertyToCompare == this.PropertyToCompare;
}
}
在你的结构中覆盖Equals
和GetHashCode
:
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);
}
}