根据条件从列表中删除重复项 [英] Remove Duplicate item from list based on condition

查看:86
本文介绍了根据条件从列表中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一类具有属性(名称,价格)的物品.

I have a class Items with properties ( Name, Price).

   Item1       $100
   Item2       $200
   Item3       $150
   Item1       $500
   Item3       $150

仅当名称存在多次且使用LINQ且价格为$ 500且未创建自定义比较器时,我才想删除项目吗?一件以上$ 500的商品将从列表中删除.

I want to remove items only if Name exists more than once and price is $500 using LINQ and without creating Custom comparer? for above one item1 with $500 will be removed from list.

谢谢

推荐答案

尝试一下:

var result = items
    .GroupBy(item => item.Name)
    .SelectMany(g => g.Count() > 1 ? g.Where(x => x.Price != 500) : g);

第一个按名称分组.如果该组中有多个项目,请从该组中选择价格不超过500的项目.

First group by name. If the group has more than 1 item, select only items from the group where the price is not 500.

这篇关于根据条件从列表中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆