简体   繁体   English

使用扩展方法按 Object 类型属性对列表进行排序 - Asp.Net Core 6

[英]Sort List by Object type property using extension method - Asp.Net Core 6

I have created an API using ASP.Net Core 6. This API used to manipulate the store products.我使用 ASP.Net Core 6 创建了一个 API。这个 API 用于操作商店产品。 The getAllProducts endpoint returns the list of products and I have added the sorting functionality to the getAllProducts(list) endpoint by using an extension method. getAllProducts 端点返回产品列表,我已使用扩展方法将排序功能添加到 getAllProducts(list) 端点。

Product Entity:产品实体:

public class Product
{
    [Required]
    [StringLength(50)]
    public string Name { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }  
    public virtual ProductCategory Category { get; set; }
}

ProductCategory entity: ProductCategory 实体:

public class ProductCategory
{
    public string Name { get; set; }
}

Extension method:扩展方法:

public static IQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> list, string orderByProperty, bool desc)
    {
        string command = desc ? "OrderByDescending" : "OrderBy";
        var type = typeof(TEntity);
        var property = type.GetProperty(orderByProperty);
        var parameter = Expression.Parameter(type, "p");
        var propertyAccess = Expression.MakeMemberAccess(parameter, property);
        var orderByExpression = Expression.Lambda(propertyAccess, parameter);
        var resultExpression = Expression.Call(typeof(Queryable), command, new Type[] { type, property.PropertyType },
            list.Expression, Expression.Quote(orderByExpression));
        return list.Provider.CreateQuery<TEntity>(resultExpression);
    }

I called the extension method this way.我这样调用了扩展方法。

productsList = productsList.AsQueryable().OrderBy("Category", true).ToList();

This works fine with all product entity properties except the 'Category'.这适用于除“类别”之外的所有产品实体属性。 It throws an exception System.InvalidOperationException: Failed to compare two elements in the array.它抛出异常System.InvalidOperationException: Failed to compare two elements in the array. when I pass 'Category' as orderByProperty.当我将“类别”作为 orderByProperty 传递时。 I want to customize the extension method so that if an object type property passed in, sort the list by name of the passed object. (by category name in this case).我想自定义扩展方法,以便如果传入 object 类型属性,则按传入的 object 的名称对列表进行排序。(在本例中按类别名称)。 I expect your help.我期待你的帮助。 Thank You.谢谢。

Runtime does not know how to compare two instances of ProductCategory so you need to provide a way for LINQ-to-Objects to do this.运行时不知道如何比较ProductCategory的两个实例,因此您需要为 LINQ-to-Objects 提供一种方法来执行此操作。 For example implementing IComparable<ProductCategory> :例如实施IComparable<ProductCategory>

public class ProductCategory : IComparable<ProductCategory>
{
    public string Name { get; set; }

    public int CompareTo(ProductCategory? other)
    {
        if (ReferenceEquals(this, other)) return 0;
        if (ReferenceEquals(null, other)) return 1;
        return string.Compare(Name, other.Name, StringComparison.Ordinal);
    }
}

Also possibly you can consider passing expression into the method:您也可以考虑将表达式传递给方法:

public static IQueryable<TEntity> OrderBy<TEntity, TProp>(this IQueryable<TEntity> list, Expression<Func<TEntity, TProp>> selector, bool desc)
{
   // change accordingly 
}

With usage changed to:用法更改为:

productsList = productsList.AsQueryable()
    .OrderBy(p => p.Category.Name, true)
    .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 向ASP.NET Core中的TempData对象添加扩展方法 - Add extension method to TempData object in asp.net core ASP.NET Core web api 序列化对象的List类型属性 - ASP.NET Core web api serialize an object's List type property 在ASP.NET Core中使用NumberFormat属性 - Using NumberFormat property in ASP.NET Core 扩展方法 C# ASP.NET 核心 - Extension Method C# ASP.NET Core 在 Asp.net 核心 web ZDB974238714CA8DE6FZACE7ACE 中反序列化抽象 object 类型集合的属性的正确方法 - Proper way to de-serialize a property of type collection of abstract object in Asp.net Core web API 在 ASP.net 核心 mvc 3.1 中的 HtmlHelper 扩展方法中使用 DataAnnotation 本地化程序 - Using DataAnnotation localizer in your extension method for HtmlHelper in ASP.net core mvc 3.1 ASP.NET 核心 3 - 可空类型 - 从 json 中删除属性 - ASP.NET Core 3 - nullable type - removes property from json 将DropdownList属性绑定到ASP.NET Core中的控制器方法 - Binding DropdownList property to controller method in ASP.NET Core 如何在 get 方法中传递类对象列表 - asp.net core 2.1 - How to pass list of class object in get method - asp.net core 2.1 将自定义模型活页夹应用于asp.net核心中的对象属性 - Apply Custom Model Binder to Object Property in asp.net core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM