开发者

Filtering a list with linq

开发者 https://www.devze.com 2023-04-09 08:01 出处:网络
Being new to linq, I am having trouble trying to apply a filter to a List object. This is what I have so far

Being new to linq, I am having trouble trying to apply a filter to a List object. This is what I have so far

var filter = productList.GroupBy(a => a.Product.FamilySku).Select(grp => grp.OrderByDescending(a => a.Product.FamilySku).First());

This works except I want to not apply the开发者_运维知识库 filter if the a.Product.IsFamily != true

I want to add an except clause:

Except(a.Product.IsFamily != true)

So in pseudo code, I want to group by all the Product.FamilySku's but not group them if Product.IsFamily != true.

Thx for the help


The other answers work if you want to completely leave out the products where IsFamily is false. But if what you want is for them to be in the filtered list, but not grouped, then you could Concat() them on at the end like this:

var filter = productList.Where(p => p.Product.IsFamily)
                        .GroupBy(p => p.Product.FamilySku)
                        .Select(grp => grp.OrderByDescending(p => p.Product.FamilySku).First())
                        .Concat(productList.Where(p => !p.Product.IsFamily));

There may be a better way to do it if you don't want to change their order.


Just put in a Where() filter before the grouping:

var filter = productList.Where(p => p.Product.IsFamily)
                        .GroupBy(a => a.Product.FamilySku)
                        .Select(grp => grp.OrderByDescending(a => a.Product.FamilySku).First());


Looks like you just need to use a the Where() method:

var filter = productList
                .Where(a => a.Product.IsFamily)
                .GroupBy(a => a.Product.FamilySku)
                .Select(grp => grp.OrderByDescending(a => a.Product.FamilySku).First());


productList.Where(!a.Product.IsFamily).GroupBy(a => a.Product.FamilySku)
    .Select(grp => grp.OrderByDescending(a => a.Product.FamilySku).First());
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号