1

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..

3
  • Can you show some code how you are retrieving the data? Commented May 10, 2012 at 7:37
  • See stackoverflow.com/questions/986572/… Commented May 10, 2012 at 7: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.. Commented May 10, 2012 at 14:22

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

You could also think about making this generic so that you can just use Equals<T>(T first, T second) where T:class to allow the same type of comparison on any 2 objects of the same class.
Thanks @Kim R, I'll consider your suggestion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.