gpt4 book ai didi

c# Linq - 从每组中选择前 2 个

转载 作者:行者123 更新时间:2023-12-02 15:23:51 25 4
gpt4 key购买 nike

我需要获取每个 ProductTypeName 的前 2 个产品:

var productDetails = (from p in products
join po in productOrganisations
on p.Id equals po.ProductId
where po.OrganisationId == id
where p.ProductTypeId == (typeId > 0 ? typeId : p.ProductTypeId) //filter by type if specified
where p.IsLive
select new
{
Id = p.Id,
Name = p.Name,
SupplierName = p.Supplier.Name,
ProductTypeName = p.ProductType.Name,
ShortDescription = p.ShortDescription,
ProductTypeId = p.ProductTypeId,
DatePublished = p.DatePublished,
CurrencyId = p.CurrencyId,

})
.AsNoTracking()
.ToArray();

目前,上述语句返回了我的所有产品,数百个。每个产品都有一个属性 ProductTypeName 。

我需要按此 ProductTypeName 进行分组,然后按发布日期降序获取每个组中的前两个。

有什么想法吗?

最佳答案

ChrisWue provides a good answer here 。如果这解决了您的问题,请给他投赞成票

严格键入您的列表,然后使用 GroupByOrderByTake 获取结果。

像这样严格输入结果集:

List<ProductDetails> myProductList = (from p in products
join po in productOrganisations
on p.Id equals po.ProductId
where po.OrganisationId == id
where p.ProductTypeId == (typeId > 0 ? typeId : p.ProductTypeId) //filter by type if specified
where p.IsLive
select new
{
Id = p.Id,
Name = p.Name,
SupplierName = p.Supplier.Name,
ProductTypeName = p.ProductType.Name,
ShortDescription = p.ShortDescription,
ProductTypeId = p.ProductTypeId,
DatePublished = p.DatePublished,
CurrencyId = p.CurrencyId,

})
.AsNoTracking()
.ToList();

然后像这样查询列表:

List<ProductDetail> finalResult = 
myProductList.GroupBy(p => p.ProductTypeName)
.SelectMany(d => d.OrderBy(r => r.DatePublished.Take(2))
.ToList();

关于c# Linq - 从每组中选择前 2 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33151065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com