Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Duplicate item from list based on condition

Tags:

c#

linq

c#-4.0

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

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

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.

Thanks,

like image 394
user570715 Avatar asked May 21 '12 21:05

user570715


People also ask

How do I remove duplicates with conditions?

Create a column Key with the following formula (i am assuming you data have headers and start from cell A1 . Then in cell C2 put the formula =IF(B2<>B3,0,1) and copy down. Finally, copy the filtered table and paste it elsewhere then select it all and Data -> Remove Duplicates and your done.

Which clause is used to remove duplicates from results?

Answer: The DISTINCT keyword is used to remove the duplicate rows in a table.


2 Answers

Try this:

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

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

like image 100
david.s Avatar answered Sep 28 '22 10:09

david.s


var result =
    from item in items
    where item.Price != 500 || items.Count(i => i.Name == item.Name) == 1
    select item;
like image 21
Helstein Avatar answered Sep 28 '22 08:09

Helstein