鉴于以下示例,我如何在第二个示例中使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
答案 0 :(得分:2)
创建一个实现IEqualityComparer的类,并在list.contains方法中传递该对象
答案 1 :(得分:1)
public class Client : IEquatable<Client>
{
public string PropertyToCompare;
public bool Equals(Client other)
{
return other.PropertyToCompare == this.PropertyToCompare;
}
}
答案 2 :(得分:1)
覆盖结构中的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();
}
}
此实现处理所有边缘情况。
阅读this question,了解为什么还要覆盖GetHashCode()
。
答案 3 :(得分: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);
}
}