C# – Remove duplicates in the list using linq

cgeneric-listlinqlinq-to-objects

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?

Best Answer

var distinctItems = items.GroupBy(x => x.Id).Select(y => y.First());