我必须比较两个幻灯片类型的列表,其中包含另一个项目列表,称为图表。我必须找到幻灯片列表之间的所有差异,其中的差异可能是:
列表 A 中的幻灯片,但不在 B 中
列表 A 中的幻灯片,但不在 B 中
两个列表中的幻灯片,但它们的图表不同
我尝试使用except,但它返回具有不同图表的列表作为“相同”。示例列表 A:ABCD 列表 B:ABCD*(d 包含不同的图表)应该返回 D*,但这不起作用。
我对为什么会发生这种情况有点困惑-比较器对我来说看起来不错。
我的代码:
class PPDetectDifferences
{
private PPPresentation laterVersion;
private string Path { get; set; }
private PPPresentation OriginalPresentation { get; set; }
private PPPresentation GetLaterPresentation()
{
var ppDal = new PPDAL(Path);
Task<PPPresentation> task = Task.Run(() => ppDal.GetPresentation());
var presentation = task.Result;
return presentation;
}
public PPDetectDifferences(string path, PPPresentation ppPresentation)
{
if (path != null)
{
this.Path = path;
}
else
{
throw new ArgumentNullException("path");
}
if (ppPresentation != null)
{
this.OriginalPresentation = ppPresentation;
}
else
{
throw new ArgumentNullException("ppPresentation");
}
}
public bool IsDifferent()
{
//// getting the new List of Slides
laterVersion = GetLaterPresentation();
//// Compare the newer version with the older version
var result = laterVersion.Slides.Except(OriginalPresentation.Slides, new PPSlideComparer()).ToList();
//// If there are no differences, result.count should be 0, otherwise some other value.
return result.Count != 0;
}
}
/// <summary>
/// Compares two Slides with each other
/// </summary>
public class PPSlideComparer : IEqualityComparer<PPSlide>
{
public int GetHashCode(PPSlide slide)
{
if (slide == null)
{
return 0;
}
//// ID is an INT, which is unique to this Slide
return slide.ID.GetHashCode();
}
public bool Equals(PPSlide s1, PPSlide s2)
{
var s1Charts = (from x in s1.Charts select x).ToList();
var s2Charts = (from x in s2.Charts select x).ToList();
var result = s1Charts.Except(s2Charts, new PPChartComparer()).ToList();
return result.Count == 0;
}
}
/// <summary>
/// Compares two Charts with each other
/// </summary>
public class PPChartComparer : IEqualityComparer<PPChart>
{
public int GetHashCode(PPChart chart)
{
//// UID is an INT, which is unique to this chart
return chart == null ? 0 : chart.UID.GetHashCode();
}
public bool Equals(PPChart c1, PPChart c2)
{
var rvalue = c1.UID == c2.UID;
if (c1.ChartType != c2.ChartType)
{
rvalue = false;
}
return rvalue;
}
}