I am using entityframework. I had two records which are retrieved from table using 'id' which is a primary key. Now i want to compare these two table records data and display the old value and new value in my view. Now my question is how to compare two records... There are almost 20 properties in my table from which i retrieve the data. We have to compare each and every property or is there are any best method... Can any one please help me to find the solution..
Asked
Active
Viewed 1,192 times
1
-
Can you show some code how you are retrieving the data? – TRR May 10 '12 at 07:37
-
See http://stackoverflow.com/questions/986572/hows-to-quick-check-if-data-transfer-two-objects-have-equal-properties-in-c/986617#986617 – Eranga May 10 '12 at 07:38
-
using (Model.SlmgDataContext dbContext = new Model.SlmgDataContext()) { var student= dbContext.Students.FirstOrDefault(con => con.id== studentid); var previousStudent = dbContext.Students.FirstOrDefault(con => con.id== previousstudentid); } Now i want to compare these two students marks.. – Swetha Bindu May 10 '12 at 14:22
1 Answers
1
public bool Equals<T>(T first, T second)
{
var f = new List<T>() {first};
var s = new List<T>() {second};
PropertyInfo[] propertyInfos = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Static);
foreach (PropertyInfo propertyInfo in propertyInfos)
{
if (f.Select(x => propertyInfo.Name).FirstOrDefault() != s.Select(x => propertyInfo.Name).FirstOrDefault())
return false;
}
return true;
}
Changed to Equals < T > (T first, T second) as Kim R recommended
Try it :) I haven't tested it

karaxuna
- 26,752
- 13
- 82
- 117
-
You could also think about making this generic so that you can just use Equals
(T first, T second) where T:class to allow the same type of comparison on any 2 objects of the same class. – Kim R May 10 '12 at 12:08 -