如何按其子列表中的值对父对象的 IQueryable 列表进行排序
How to order a IQueryable list of parent objects by a value in it's childs list
我正在尝试根据特定规范 TypeId 的 TextValue 按复杂对象的子列表对复杂对象的父列表进行排序。
我有以下 类:
public class Product
{
public long Id {get;set;}
public string Name {get;set;}
public List<Specification> Specifications {get;set;}
}
public class Specification
{
public long Id {get;set;}
public long TypeId {get;set;}
public string TextValue {get;set;}
}
我想根据产品的特定规格对我的产品进行分类。
示例用例:根据 TypeId = 3 的规范的 TextValue 对产品进行排序。(一个产品只能有一个 TypeId 为 3 的规范)
我的产品列表如下所示:
IQueryable<Product> productQuery = _context.Products.Include("Specifications");
SortTypeId 是我要订购产品列表的规范类型。
这是我尝试做的:
productQuery = productQuery
.OrderBy(pq => pq.Specifications
.OrderBy(s => s.TypeID == SortTypeID ? Int32.MinValue : s.Id)
.ThenBy(v => v.TextValue));
这给出了以下异常:
System.ArgumentException: 'DbSortClause expressions must have a type that is order comparable.
Parameter name: key'
我还尝试通过带有 Indexof 的 sortedProductIds 列表对 IQueryable 进行排序,但这也不起作用(延迟加载的 IQueryable 不支持 IndexOf)。
既然你说一个产品只能有一个 SortTypeID
类型的规格,如果你在查询中加入那个规格并按它排序会怎么样?
下面是我尝试建议使用查询语法的一些示例。
from p in _context.Products.Include("Specifications")
join orderSpec in _context.Specifications on new { ProductID = p.Id, TypeID = 3 }
equals new { ProductID = orderSpec.ProductId, TypeID = orderSpec.TypeID } into os
from orderSpec in os.DefaultIfEmpty()
orderby orderSpec != null ? orderSpec.TextValue : p.Id
select p
希望对您有所帮助!
我正在尝试根据特定规范 TypeId 的 TextValue 按复杂对象的子列表对复杂对象的父列表进行排序。
我有以下 类:
public class Product
{
public long Id {get;set;}
public string Name {get;set;}
public List<Specification> Specifications {get;set;}
}
public class Specification
{
public long Id {get;set;}
public long TypeId {get;set;}
public string TextValue {get;set;}
}
我想根据产品的特定规格对我的产品进行分类。 示例用例:根据 TypeId = 3 的规范的 TextValue 对产品进行排序。(一个产品只能有一个 TypeId 为 3 的规范)
我的产品列表如下所示:
IQueryable<Product> productQuery = _context.Products.Include("Specifications");
SortTypeId 是我要订购产品列表的规范类型。
这是我尝试做的:
productQuery = productQuery
.OrderBy(pq => pq.Specifications
.OrderBy(s => s.TypeID == SortTypeID ? Int32.MinValue : s.Id)
.ThenBy(v => v.TextValue));
这给出了以下异常:
System.ArgumentException: 'DbSortClause expressions must have a type that is order comparable.
Parameter name: key'
我还尝试通过带有 Indexof 的 sortedProductIds 列表对 IQueryable 进行排序,但这也不起作用(延迟加载的 IQueryable 不支持 IndexOf)。
既然你说一个产品只能有一个 SortTypeID
类型的规格,如果你在查询中加入那个规格并按它排序会怎么样?
下面是我尝试建议使用查询语法的一些示例。
from p in _context.Products.Include("Specifications")
join orderSpec in _context.Specifications on new { ProductID = p.Id, TypeID = 3 }
equals new { ProductID = orderSpec.ProductId, TypeID = orderSpec.TypeID } into os
from orderSpec in os.DefaultIfEmpty()
orderby orderSpec != null ? orderSpec.TextValue : p.Id
select p
希望对您有所帮助!