根据条件从列表中删除重复项

根据条件从列表中删除重复项

问题描述:

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

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.