[英]Sort List by Object type property using extension method - Asp.Net Core 6
我使用 ASP.Net Core 6 創建了一個 API。這個 API 用於操作商店產品。 getAllProducts 端點返回產品列表,我已使用擴展方法將排序功能添加到 getAllProducts(list) 端點。
產品實體:
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 實體:
public class ProductCategory
{
public string Name { get; set; }
}
擴展方法:
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);
}
我這樣調用了擴展方法。
productsList = productsList.AsQueryable().OrderBy("Category", true).ToList();
這適用於除“類別”之外的所有產品實體屬性。 它拋出異常System.InvalidOperationException: Failed to compare two elements in the array.
當我將“類別”作為 orderByProperty 傳遞時。 我想自定義擴展方法,以便如果傳入 object 類型屬性,則按傳入的 object 的名稱對列表進行排序。(在本例中按類別名稱)。 我期待你的幫助。 謝謝。
運行時不知道如何比較ProductCategory
的兩個實例,因此您需要為 LINQ-to-Objects 提供一種方法來執行此操作。 例如實施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);
}
}
您也可以考慮將表達式傳遞給方法:
public static IQueryable<TEntity> OrderBy<TEntity, TProp>(this IQueryable<TEntity> list, Expression<Func<TEntity, TProp>> selector, bool desc)
{
// change accordingly
}
用法更改為:
productsList = productsList.AsQueryable()
.OrderBy(p => p.Category.Name, true)
.ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.