【发布时间】:2013-10-20 10:48:25
【问题描述】:
我想要一些关于我们如何最好地编写一个通用函数来比较两个列表的反馈。 Lists 包含类对象,我们希望遍历一个列表,在第二个 List 中查找相同的项目并报告任何差异。
我们已经有了一个比较类的方法,所以我们需要关于如何从两个列表中提供方法(如下所示)的反馈。
例如,假设我们有一个简单的“Employee”类,它具有三个属性:Name、ID、Department。我们要报告 List 和另一个 List 之间的差异。
注意:
两个列表将始终包含相同数量的项目。
如上所述,我们有一个泛型方法用于比较两个类,我们如何结合这个方法来满足列表的需求,即从另一个方法循环遍历列表并将类提供给泛型方法.. .. 但是我们如何在第二个 List 中找到等效的类以传递给下面的方法;
public static string CompareTwoClass_ReturnDifferences<T1, T2>(T1 Orig, T2 Dest)
where T1 : class
where T2 : class
{
// Instantiate if necessary
if (Dest == null) throw new ArgumentNullException("Dest", "Destination class must first be instantiated.");
var Differences = CoreFormat.StringNoCharacters;
// Loop through each property in the destination
foreach (var DestProp in Dest.GetType().GetProperties())
{
// Find the matching property in the Orig class and compare
foreach (var OrigProp in Orig.GetType().GetProperties())
{
if (OrigProp.Name != DestProp.Name || OrigProp.PropertyType != DestProp.PropertyType) continue;
if (OrigProp.GetValue(Orig, null).ToString() != DestProp.GetValue(Dest, null).ToString())
Differences = Differences == CoreFormat.StringNoCharacters
? string.Format("{0}: {1} -> {2}", OrigProp.Name,
OrigProp.GetValue(Orig, null),
DestProp.GetValue(Dest, null))
: string.Format("{0} {1}{2}: {3} -> {4}", Differences,
Environment.NewLine,
OrigProp.Name,
OrigProp.GetValue(Orig, null),
DestProp.GetValue(Dest, null));
}
}
return Differences;
}
任何建议或想法表示赞赏?
编辑:以 .NET 2.0 为目标,因此 LINQ 是不可能的。
【问题讨论】:
-
大声笑...不,一个顶级的系统关键应用程序 :-) 认真地尝试将此功能实现到一个小型爱好应用程序中...它所有的学习。
-
列表的长度是否相等?
-
等于 ??我很高兴能把它当作一个学习练习。你能扩展吗?
-
糟糕,我删除了评论。我的意思是将对象与 ID 属性等同起来。并为相同 ID 的对象添加 GetDiffereces() 方法。然后使用 LINQ。
-
@pedro:LINQ 可以在 .NET 2.0 上运行。见code.google.com/p/linqbridge