我有一个名为 FooObject 的对象:
public class FooObject
{
public string Test1 {get; set;}
public List<FooSubObject> SubTest1 {get; set;}
}
对于本例后面的内容,我还有 DifferenceFooObject :
public class DifferenceFooObject
{
public string SharedTest1 { get; set; }
public List<FooSubObject> SubTest1 {get; set;}
}
对于本例后面的内容,我还有一个 FooSubObject 。 FooObject 的属性 SubTest1 包含此类型的类型集合:
public class FooSubObject
{
public string Test2 { get; set; }
}
我有一个接受 FooObject 的类型集合的方法。在这个方法中,我需要计算类型化集合参数中 FooObjects 之间的任何属性是否具有相同的属性。
public DifferenceFooObject RunPropComparison(List<FooObject> foos)
{
DifferenceFooObject difference = new DifferencFooObject();
FooObject forComparison = foos.FirstOrDefault();
IEnumerable<FooObject> intersectCollection = foos.Skip(1);
// maybe do this using the first to compare the rest? No clue
}
我不知道完成上述方法的最有效方法。更复杂的是,至少恕我直言,计算必须考虑集合中对象的属性,这些属性是FooObject的属性(循环遍历FooSubObject的属性)。
这是请求的输入/输出:
List<FooObject> foos = new List<FooObject>();
FooObject obj = new FooObject();
obj.Test1= "Test1";
obj.SubTest1 = new List<FooSubObject>();
FooSubObject obj2 = new FooSubObject();
obj2.Test2 = "Test2";
obj.SubTest1.Add(obj2);
FooObject obj3 = new FooObject();
obj3.Test1= "Test1";
obj3.SubTest1 = new List<FooSubObject>();
FooSubObject obj4 = new FooSubObject();
obj4.Test2 = "Test3";
obj3.SubTest1.Add(obj2);
那会是什么,理想情况下,它会返回Test1是全面的。
答案 0 :(得分:0)
我认为没有一种特别有效的方法。您将需要使用getProperties方法严重依赖Reflection来获取对象属性的值......
你可以考虑使用FasterFlect(http://fasterflect.codeplex.com/),它比标准的.Net反射具有更好的性能......
答案 1 :(得分:0)
我能说的最好,这就是你要找的东西:
public IList<DifferenceFooObject> RunPropComparison(List<FooObject> foos)
{
var differences = new List<DifferenceFooObject>();
foreach (var group in foos.GroupBy(x => x.Test1))
{
var difference = new DifferenceFooObject();
difference.SharedTest1 = group.Key;
difference.SubTest1 = group.SelectMany(x => x.SubTest1).ToList();
differences.Add(difference);
}
return differences;
}
或者,如果添加以下构造函数:
public DifferenceFooObject(string sharedTest1, IEnumerable<FooSubObject> subTest1)
{
this.SharedTest1 = sharedTest1;
this.SubTest1 = subTest1.ToList();
}
然后你可以缩短这段代码:
public IList<DifferenceFooObject> RunPropComparison(List<FooObject> foos)
{
return foos.GroupBy(x => x.Test1)
.Select(g => new DifferenceFooObject(g.Key, g.SelectMany(x => x.SubTest1)))
.ToList();
}
答案 2 :(得分:0)
查看此库。它比较两个对象并告诉您不同的属性http://comparenetobjects.codeplex.com/documentation