Is there a fast way this could be done or I need to do
foreach
for every object and compare individual properties one by one?
If by "fast" you mean "performant" then comparing property-by property is probably the fastest way. If by "fast" you mean "less code to write" then you could use reflection to loop through the properties and compare the values of each item.
Note that you'll probably spend more time researching, writing, and debugging the reflection algorithm that you would just hand-coding the property comparisons.
A simple way to use the built-in Linq methods would be do define an IEqualityComparer<Model>
that defines equality of two Model
objects:
class ModelEqualityComparer : IEqualityComparer<Model>
{
public bool Equals(Model m1, Model m2)
{
if(m1 == null || 2. == null)
return false;
if (m1.Prop1 == m2.Prop1
&& m1.Prop2 == m2.Prop2
&& m1.Prop3 == m2.Prop3
...
)
{
return true;
}
else
{
return false;
}
}
public int GetHashCode(Model m)
{
int hCode = m.Prop1.GetHashCode();
hCode = hCode * 23 + ^ m.Prop2.GetHashCode();
hCode = hCode * 23 + ^ m.Prop32.GetHashCode();
...
return hCode;
}
}