Remove duplicate item from list depending on condition

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

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

I want to delete elements only if the name exists more than once and the price is $ 500 using LINQ and without creating a custom mapping? for more than one item1 with $ 500 will be removed from the list.

Thank,

+5
source share
7 answers

Try the following:

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

The first group is by name. If a group has more than one element, select only elements from the group where the price is not 500.

+8
source
var result =
    from item in items
    where item.Price != 500 || items.Count(i => i.Name == item.Name) == 1
    select item;
+4
source

, :

var dupes = list.Where(a => list.Count(b => b.Name.Equals(a.Name)) > 1).ToList();

.ToList() , . , .

, List<>, RemoveAll():

list.RemoveAll(item => item.Price == 500 && dupes.Contains(item));

.

IEnumerable<>, , LINQ:

var result = list.Where(item => !(item.Price == 500 && dupes.Contains(item)));

result.

+3

:

var dups = lst.Where(x=>lst.Any(y => y != x && y.Name == x.Name))

500 :

var dups500 = dups.Where(x=>x.Price == 500);

, dups500 except:

var result = lst.Except(dup);

:

var result = 
     lst.Except(
               lst
               .Where(x=>x.Price == 500 && 
                         lst.Any(y => y != x && y.Name == x.Name))).ToList();
+2
var result = from np in NamePriceCollection
where NamePriceCollection.Count(x => x.Name == np.Name) > 1 && np.Price == 500
select np;

// you have a list of items for the specified condition. Remove them from the main collection.

+1
source

I want to delete items only if the name exists more than once and the price is $ 500

Apple 300 <-- winner
Apple 500 <-- dupe
Banana 500  <-- winner
Banana 500  <-- dupe
Banana 500  <-- dupe
Cantelope 100 <-- winner
Cantelope 200 <-- winner

The second apple is a hoax, obviously. A banana has three items with a price == 500. One of them is the winner. The rest are deceptions. No price == 500 Cantelopes, so there is no cheating, just winners.

from item in source
group item by item.Name into g
let okItems = g.Where(x => x.Price != 500)
let secondChoiceItem = g.FirstOrDefault(x => x.Price == 500)
let theItems = okItems.DefaultIfEmpty(secondChoiceItem)
from nonDupeItem in theItems
select nonDupeItem
0
source
var Test = (from row in DataTable.AsEnumerable()
            select row.Field<string>("ColumnName")).Distinct();
-2
source

All Articles