在我的“发票”类中,它具有20多个字段,我需要支持对所有字段的排序。

我有一个接受属性字符串的方法(例如“ AmountDue”)。现在,我需要OrderBy AmoundDue字段。

我的具体要求是,传递一个属性名称字符串值,我想返回一个函数,

Func<Invoice, decimal> keySelector = a=> a.AmountDue;

动态构建整个表达式的位置。

我可以在其中使用keySelector进行排序

_api.Invoices.Find().Where(c => c.Contact.Id == contactId).OrderBy(keySelector).ToList();


到目前为止,我已经能够使用字符串值识别类型。需要一些帮助来返回函数。

  public static Type VariableType(string prop)
    {
        Type type = typeof(TResource);
        PropertyInfo pi = type.GetProperty(prop, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
        type = pi.PropertyType;
        return type;
    }



  在发布此问题之前,我曾提及this post。输入正在
  两个问题都被认为是相同的,但输出却不同。一世
  尝试使用该解决方案并尝试,但无法解决我的问题
  具体问题。就我而言,我正在调用第三方API(Xero
  api),我想专门构建此输出。

最佳答案

排序时,您必须返回属性值,而不是类型或属性本身

  String propertyName = "AmountDue";

  var result = _context
    .Invoices
    .Find()
    .Where(c => c.Contact.Id == contactId)
    .OrderBy(item => typeof(Invoice).GetProperty(
         propertyName,
         BindingFlags.Public | BindingFlags.Instance)
       .GetValue(item))
    .ToList();

09-04 10:51