我有一个对象,它具有属性ID,brandID,brandName,NumPages和Type。使用lambda筛选列表
我需要显示前5个品牌被numPage大小,一个品牌可能有多个ID,所以我需要按品牌
listing.OrderByDescending(o => o.numPage).GroupBy(o=> o.brandName).Take(5).ToList();
是孤独的什么即时寻找的线条,但这不是有效的代码。
我有一个对象,它具有属性ID,brandID,brandName,NumPages和Type。使用lambda筛选列表
我需要显示前5个品牌被numPage大小,一个品牌可能有多个ID,所以我需要按品牌
listing.OrderByDescending(o => o.numPage).GroupBy(o=> o.brandName).Take(5).ToList();
是孤独的什么即时寻找的线条,但这不是有效的代码。
这听起来像一个给定的品牌名称可能有几个ID,并且你想要前5名品牌按numPage排序。是正确的
如果是的话请尝试以下
var query = listing
.GroupBy(x => x.brandName)
.OrderByDescending(brands => brands.Sum(x => x.numPage))
.Select(x => x.Key)
.Take(5);
注:GroupBy
操作后你现在绕过品牌的集合对象,而不是单一的。因此,要订购numPage
,我们需要对该组中的所有品牌对象进行求和。该.Select(x => x.Key)
将选择背出哪个组是基于
只是尝试了全新的brandName
和它的作品:
public class Listing
{
public int ID { get; set; }
public int BrandID { get; set; }
public string BrandName { get; set; }
public int NumPages { get; set; }
public Type Type { get; set; }
}
这里过滤
Listing listing1 = new Listing() { NumPages = 2, BrandName = "xx" };
Listing listing2 = new Listing() { NumPages = 2, BrandName = "xx" };
Listing listing3 = new Listing() { NumPages = 2, BrandName = "xx" };
Listing listing4 = new Listing() { NumPages = 3, BrandName = "xxxxx" };
List<Listing> allListings = new List<Listing>() { listing1, listing2, listing3, listing4 };
var result = allListings.OrderByDescending(x => x.NumPages).GroupBy(x => x.BrandName).Take(5);
为什么它没有被有效?你是否收到错误信息或者没有得到想要的结果。 – 2012-01-14 00:18:30