C# c Linq-从每组中选择前2名
我需要为每个ProductTypeName获取前2个产品:C# c Linq-从每组中选择前2名,c#,linq,group-by,C#,Linq,Group By,我需要为每个ProductTypeName获取前2个产品: var productDetails = (from p in products join po in productOrganisations on p.Id equals po.ProductId where po.OrganisationId == id
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分组,然后按datepublished降序获得每组中前两名
有什么想法吗?对于任何有相同问题的人,我最终使用以下方法解决:
.GroupBy(x => x.ProductTypeId)
.SelectMany(x => x.Take(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,
})
.GroupBy(x => x.ProductTypeId)
.SelectMany(x => x.Take(2))
.AsNoTracking()
.ToArray();
这很有效,但我想知道这是最好的方法吗?效率最高?。如果这能解决你的问题,那就投他一票
强烈键入列表,然后使用GroupBy、OrderBy和Take获得结果
按如下方式强键入结果集:
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();
使用take功能,使您的解决方案看起来坚固。我认为它可能缺少DatePublished上的“OrderBy”。这在许多情况下都非常有用和正确,但在我的实际情况中,我在这一点上没有强类型,因为我的结果集实际上有额外的列用于存储计算值,稍后我从这些列中选择并传递给强类型结果集。