0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

GetPropertyInfo

Posted at

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

public static class ListSorter
{
public static List SortByProperty(List list, string propertyName, bool descending = false)
{
if (string.IsNullOrEmpty(propertyName)) return list;

    PropertyInfo prop = typeof(T).GetProperty(propertyName,
        BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
    if (prop == null) throw new ArgumentException($"Property '{propertyName}' not found.");

    return descending
        ? list.OrderByDescending(x => prop.GetValue(x, null)).ToList()
        : list.OrderBy(x => prop.GetValue(x, null)).ToList();
}

}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?