Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicates in the list using linq

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

The List of Items is populated with duplicated items.

For ex.:

1         Item1       IT00001        $100 2         Item2       IT00002        $200 3         Item3       IT00003        $150 1         Item1       IT00001        $100 3         Item3       IT00003        $150 

How to remove the duplicates in the list using linq?

like image 331
Prasad Avatar asked Oct 22 '09 11:10

Prasad


People also ask

Does Linq Union remove duplicates?

Linq, acts upon 2 collections. It returns a new collection that contains the elements that are found. Union removes duplicates. So this method can be thought of as two actions: it combines the two collections and then uses Distinct() on them, removing duplicate elements.

Which operator filter the elements of a sequence based on a type?

The Where operator (Linq extension method) filters the collection based on a given criteria expression and returns a new collection. The criteria can be specified as lambda expression or Func delegate type.


1 Answers

var distinctItems = items.GroupBy(x => x.Id).Select(y => y.First()); 
like image 126
Freddy Avatar answered Oct 12 '22 00:10

Freddy