Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

How to compare two objects in c#

I have a method to update some customer information

public UpdateCustomerInformationResponse UpdateCustomerInformation(UpdateCustomerInformationRequest request)
{
var customer = new Customer
{
    FirstName = request.Customer
    LastName = request.LastName,
    MiddleInitial = request.MiddleInitial,
    CustomerEmail = request.CustomerEmail,
    UnitNumber = request.UnitNumber,
}

Another object

var fieldRequired = new FieldRequired{
FieldName = "CustomerEmail ",
IsRequired = 1
}

I want to compare 2 objects so that I can find out if FieldName "CustomerEmail" is present in Customer object.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Its so simple buddy. I found a simple solution using the reflection and extnetion method just follow as below

Create a static class with the name "CompareTwoObjects" and add the code to it.

 public static object CompareEquals(this T objectFromCompare, T objectToCompare)//Generic method

{

 if (objectFromCompare == null && objectToCompare == null)
 return true;
 else if (objectFromCompare == null && objectToCompare != null)
 return false;
 else if (objectFromCompare != null && objectToCompare == null)
 return false;

 //Gets all the properties of the class
 PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
 foreach (PropertyInfo prop in props)
 {
 object dataFromCompare = objectFromCompare.GetType().GetProperty(prop.Name).GetValue(objectFromCompare, null);
 object dataToCompare = objectToCompare.GetType().GetProperty(prop.Name).GetValue(objectToCompare, null);
 Type type = objectFromCompare.GetType().GetProperty(prop.Name).GetValue(objectToCompare, null).GetType();
 if (prop.PropertyType.IsClass && !prop.PropertyType.FullName.Contains("System.String"))
 {
 dynamic convertedFromValue = Convert.ChangeType(dataFromCompare, type);
 dynamic convertedToValue = Convert.ChangeType(dataToCompare, type);

 object result = CompareTwoObjects.CompareEquals(convertedFromValue, convertedToValue);

 bool compareResult = (bool)result;
 if (!compareResult)
 return false;
 }


 else if (!dataFromCompare.Equals(dataToCompare))
 return false;
 }

 return true;


}

This will give the result of two objects are having same values or not.

Usage:- Object1.CompareEquals(Object2);

If the class object is complex also this will work. If you found any issues please post back


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...