Reputation: 15430
I want to find out the missing properties in one class by comparing the other class
public class User
{
public int UserID { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class UserDTO
{
public string UserName { get; set; }
public string FirstName { get; set; }
}
Above I should get the output like "UserID, "LastName" properties are missing in UserDTO.
Upvotes: 0
Views: 127
Reputation: 35353
var list = typeof(User).GetProperties().Select(x => x.Name)
.Except(typeof(UserDTO).GetProperties().Select(y => y.Name))
.ToList();
EDIT
Including suggestions in comments and public Fields
public static IEnumerable<string> Diff(Type t1, Type t2)
{
return t1.GetProperties().Select(p1 => new { Name = p1.Name, Type = p1.PropertyType })
.Concat(t1.GetFields().Select(f1 => new { Name = f1.Name, Type = f1.FieldType }))
.Except(t2.GetProperties().Select(p2 => new { Name = p2.Name, Type = p2.PropertyType })
.Concat(t2.GetFields().Select(f2 => new { Name = f2.Name, Type = f2.FieldType })))
.Select(a => a.Name);
}
Upvotes: 10
Reputation: 5746
Use reflection to get the properties, see Type.GetProperties. Then compare both property lists to find the missing ones.
var UserProperties = typeof(User).GetProperties().Select(p => p.Name);
var UserDTOProperties = typeof(UserDTO).GetProperties().Select(p => p.Name);
var missingProperties = UserProperties.Except(UserDTOProperties);
Take into account that all inherited properties will also be present in these lists, unless yous specify BindingFlags.DeclaredOnly
to the GetProperties()
method, see BindingFlags.
Upvotes: 7