vendredi 13 novembre 2020

Match a list of properties in a class with a list of strings

I have this object:

 public partial class Subjects
{
    public Guid SubjectId { get; set; }
    public string Code { get; set; }
    public Guid OrganizationId { get; set; }
    public string PreferredName { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public DateTime? DateOfBirth { get; set; }
    public string Gender { get; set; }
    public string LastNameInitial { get; set; }
    public string CodeDisplay { get; set; }
    public Guid? RaceId { get; set; }
    public Guid? MaritalStatusId { get; set; }
    public Guid? StatusId { get; set; }
    public string Rank { get; set; }
    public string Email { get; set; }
    public string MobilePhone { get; set; }
    public bool MobilePhoneDoNotLeaveMsg { get; set; }
    public bool MobilePhoneDoNotText { get; set; }
    public string WorkPhone { get; set; }
    public bool WorkPhoneDoNotLeaveMsg { get; set; }
}

And I have this list of strings that are names of the properties in the class that I need to encrypt:

public static List<string> EncryptedColumns = new List<string> { "SocialSecurityNumber", "CodeDisplay", "FirstName", "LastName", "MiddleName", "PreferredName", "LastNameInitial" };

Right now the way these two strings match is using reflection to check each item in the list to a property in the class. If there was a match, the value was encrypted. I want to avoid using reflection for this due to the overhead. Here is how the current program does this matching:

            foreach (string name in EncryptedColumns)
            {
                var property = encryptSubject.GetType().GetProperty(name);
                if (property != null)
                {
                    var value = property.GetValue(encryptSubject , null);
                    if (value != null)
                    {
                        string finalvalue = value.ToString();
                        
                        property.SetValue(encryptSubject, Encrypt(finalvalue), null);
                    }
                }
            }

This does work, but reflection carries a lot of overhead. Is there a better method for doing this?





Aucun commentaire:

Enregistrer un commentaire