有没有一种简单的方法可以比较两个集合?
我所拥有的是以下内容:
ICollection<AnswerDetail> rfc; // Responses from Client
ICollection<AnswerDetail> afd; // Answer from Database
我想有办法比较两个集合并检查是否
rfc中Response
字段的值与afd中Correct
字段的值匹配
这是AnswerDetail类:
public class AnswerDetail
{
public int AnswerId { get; set; }
public string Text { get; set; }
public Nullable<bool> Correct { get; set; }
public Nullable<bool> Response { get; set; }
}
答案 0 :(得分:1)
如果已经订购了集合,您可以实现比较器:
public class FancyComparer : IEqualityComparer<AnswerDetail>
{
public bool Equals(AnswerDetail x, AnswerDetail y)
{
return x.AnswerId == y.AnswerId && x.Correct == y.Response;
}
public int GetHashCode(AnswerDetail obj)
{
return obj.AnswerId;
}
}
然后使用sequence equals:
var equlas = afd.SequenceEqual(rfc, new FancyComparer());
如果没有订购,那么您必须先订购它们(例如,使用OrderBy
)
var equals = afd.OrderBy(x => x.AnswerId)
.SequenceEqual(rfc.OrderBy(x => x.AnswerId), new FancyComparer());
答案 1 :(得分:0)
bool RfcEqualsAfd=rfc.All(q=>
afd.Any(a=>
q.Response==a.Correct &&
q.AnswerId==a.AnswerId
)
);