:::: MENU ::::

Distinct with LINQ

Here is one more LINQ Problem.

Let’s think of scenario having record as below

ProductId:1 , ProductName=”Product 1″ , CategoryId=2;
ProductId:2 , ProductName=”Product 2″ , CategoryId=3;
ProductId:3 , ProductName=”Product 3″ , CategoryId=1;
ProductId:4 , ProductName=”Product 4″ , CategoryId=1;
ProductId:4 , ProductName=”Product 5″ , CategoryId=2;`

And we want the records of Product 1,Product 2, Product 3 (which are actually distinct according to our requirement for CategoryId).
Here if we use distinct in our select query then it will return all(above 5 records) the Product records.

So, to achieve our requirement we need to use GroupBy like below:

List<Product> DistinctProduct = AllProduct.GroupBy(product => product.CategoryId).Select(products => products.First()).ToList();

We can also define groups on multiple properties, like below:

List<Product> DistinctProduct = AllProduct.GroupBy(product => product.CategoryId, product.Name).Select(products => products.First()).ToList();

There must be other simpler ways to achieve above.

If you have any suggestions for improvement let me know in comments.

Happy Coding !!

One Comment

So, what do you think ?