[英]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.