dimanche 9 mai 2021

Order Generic C# list using reflection and enum property

I have a generic method that Order a List of T objects using the name of one of the properties.

This is my class:

public class TeamMember
{
    public string Name { get; set; }
    public TeamRole Role { get; set; }
}
public enum TeamRole
{
    Admin,
    User,
    Client
}

And this is the simplified method

public List<T> Sort(List<T> Items, string SortProperty)
{
    var propertyInfo = Items[0].GetType().GetProperty(SortProperty, BindingFlags.Public | BindingFlags.Instance);

    Items = Items.OrderBy(e => propertyInfo.GetValue(e, null)).ToList();
    return Items;

}

All works with a string property, calling Sort() passing a List and "Name" as SortProperty.

How can I update this method to accept the enum "Role" as SortProperty and OrderBy Role?





Aucun commentaire:

Enregistrer un commentaire