我一直在阅读如何将列表与一个人进行比较。我试图实现IEquatable
接口。以下是我到目前为止所做的事情:
/// <summary>
/// A object holder that contains a service and its current failcount
/// </summary>
public class ServiceHolder : IEquatable<ServiceHolder>
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="service"></param>
public ServiceHolder(Service service)
{
Service = service;
CurrentFailCount = 0;
}
public Service Service { get; set; }
public UInt16 CurrentFailCount { get; set; }
/// <summary>
/// Public equal method
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
ServiceHolder tmp = obj as ServiceHolder;
if (tmp == null)
{
return false;
}
else
{
return Equals(tmp);
}
}
/// <summary>
/// Checks the internal components compared to one annother
/// </summary>
/// <param name="serviceHolder"></param>
/// <returns>tru eif they are the same else false</returns>
public bool Equals(ServiceHolder serviceHolder)
{
if (serviceHolder == null)
{
return false;
}
if (this.Service.Id == serviceHolder.Service.Id)
{
if (this.Service.IpAddress == serviceHolder.Service.IpAddress)
{
if (this.Service.Port == serviceHolder.Service.Port)
{
if (this.Service.PollInterval == serviceHolder.Service.PollInterval)
{
if (this.Service.ServiceType == serviceHolder.Service.ServiceType)
{
if (this.Service.Location == serviceHolder.Service.Location)
{
if (this.Service.Name == this.Service.Name)
{
return true;
}
}
}
}
}
}
}
return false;
}
}
这就是我使用它的地方:
private void CheckIfServicesHaveChangedEvent()
{
IList<ServiceHolder> tmp;
using (var db = new EFServiceRepository())
{
tmp = GetServiceHolders(db.GetAll());
}
if (tmp.Equals(Services))
{
StateChanged = true;
}
else
{
StateChanged = false;
}
}
现在当我调试并在equals函数中放置一个断点时,它永远不会被击中。
这导致我认为我已经错误地实现了它或者我没有正确地调用它?
答案 0 :(得分:3)
如果要比较两个列表的内容,则最佳方法是SequenceEqual
。
if (tmp.SequenceEquals(Services))
这将使用列表中的值使用相等语义来比较两个列表的内容。在这种情况下,元素类型为ServiceHolder
,并且您已经为此类型定义了相等语义,它应该可以正常工作
修改强>
OP评论说,收集的顺序无关紧要。对于该场景,您可以执行以下操作if (!tmp.Except(Services).Any())
答案 1 :(得分:0)
您可以使用linq轻松比较没有订单的列表。
List<ServiceHolder> result = tmp.Except(Services).ToList();