Linq – Distinct by a particular column



I had a list of tags for a particular user. I wanted to show only unique tags. I initially thought there would be something an inbuilt ‘distinct’ operator in Linq. Unfortunately not. I then discovered the Distinct() function. But it doesn’t support filtering the results by a particular column.

Thanks to this StackOverflow question that set my direction. It says that I must use the ‘group by’ operator, which I did.

Following is the code that I ended up with:

1
2
3
4
5
//distinct tags for a particular user
var tags = from t in _db.Tags 
               where t.UserId == userId
               group t by t.Name into g
               select g.FirstOrDefault();

Since the query returns a group, we must select the first item in the group. Hence FirstOrDefault().

Thanks.



Leave a Reply

Your email address will not be published. Required fields are marked *