LTsetskhla
LTsetskhla

Reputation: 33

how to compare enum elements list to enum list c#

Hi i have a ENUM like

Elementary_Education = 1,
High_School_Incomplete = 2,
High_School_Complete = 3,
Secondary_Technical_Or_Vocational = 5,
Vocational_Education_Student = 7,
Higher_Education_Institution__Student = 9

Then i have person for example who has some of this educations for example he has this three: High_School_Incomplete High_School_Complete Secondary_Technical_Or_Vocational

this i want is to get from this 3 the highest value in this example : Secondary_Technical_Or_Vocational .

For example result.degree is Enum element it must get the value of enum i want. applicant.Educations is list of educations . each has 1 degree element. iwant to compare each raw and get the highest enum element degree.

result.Degree = applicant.Educations.Where(x => (int)x.Degree)

Upvotes: 1

Views: 631

Answers (3)

Andrei Dragotoniu
Andrei Dragotoniu

Reputation: 6335

the question is not very clear so I made some assumptions. It looks like a person as you call it, has a list of educations which would be a list of degrees, each having an enum value

you want to get the highest value from that list and translate it into an enum value.

so with a code setup like this :

 public class Person
{
    public List<Education> Educations = new List<Education>();
}

public class Education
{
    public Enums.DegreeType Degree { get; set; }
}

public class Enums
        {
            public enum DegreeType
            {
                Elementary_Education = 1,
                High_School_Incomplete = 2,
                High_School_Complete = 3,
                Secondary_Technical_Or_Vocational = 5,
                Vocational_Education_Student = 7,
                Higher_Education_Institution__Student = 9
            }
        }

we can now do something like this :

 var person = new Person();
            person.Educations.Add(new Education { Degree = Enums.DegreeType.High_School_Complete });
            person.Educations.Add(new Education { Degree = Enums.DegreeType.Vocational_Education_Student });

            var highestEd = person.Educations.Select(p => (int)p.Degree).Max();
            Enums.DegreeType enumHighest;
            Enum.TryParse(highestEd.ToString(), out enumHighest);

notice how I extract the highest education from the list and then I can parse it back to its enum value if needed.

Upvotes: 0

Piflik
Piflik

Reputation: 351

The simplest way would be to sort the degrees and then take the first.

result.Degree = applicant.Educations.OrderByDescending(x => x.Degree).FirstOrDefault();

Edit: Forgot about Max.That is even better.

Upvotes: 0

Sweeper
Sweeper

Reputation: 270790

You can get the maximum degree using Max. To assign to result, you need cast it back to your enum type:

result.Degree = (NameOfYourEnum)list.Max(x => x.Degree);

Upvotes: 1

Related Questions