samedi 29 octobre 2022

Compare between 2 class properties dynamic

I have this person class

    public class Person : IPerson
    {
        public Person(int id, string fullName, int salary, int age, decimal height)
        {
            Id = id;
            FullName = fullName;
            Salary = salary;
            Age = age;
            Height = height;
            InitTimer();
        }

        public int Id { get; private set;}

        public string FullName { get; private set;}

        public int Salary { get; private set;}

        public int Age { get; private set;}

        public decimal Height { get; private set;}
}

I want by user input (for the name of the property) to compare which value is bigger (between existing value and what we wanna add now).

        public IPerson Run(IPerson MaxOrMinPerson, string PropertyName, IPerson PersonToAdd)
        {
            var currentMaxMinPerson = MaxOrMinPerson.GetType().GetProperties().Where(x => x.Name.ToLower() == PropertyName).FirstOrDefault().GetValue(MaxOrMinPerson, null);
            var currentMaxMinPersonType = MaxOrMinPerson.GetType().GetProperties().Where(x => x.Name.ToLower() == PropertyName).FirstOrDefault();
            var personToAddPropertyValue = PersonToAdd.GetType().GetProperties().Where(x => x.Name.ToLower() == PropertyName).FirstOrDefault().GetValue(PersonToAdd, null);
            var personToAddPropertyValueType = PersonToAdd.GetType().GetProperties().Where(x => x.Name.ToLower() == PropertyName).FirstOrDefault();

            return TheBiggerValueBetweenCurrentMaxMinPersonAndPersonToAdd
        }

I'm getting the value but as object. the value could be any of the class members types (int, string, decimal).

how can I do it dynamically?





Aucun commentaire:

Enregistrer un commentaire