linq distinct – create a distinct collection using linq (c#)

Hi there,

well its been a long while since i wrote anything on this blog, alot have changed in this long period.

wanted to share a neat way to use linq in c# to get a distinct list of elements by some key.
lets say you have a collection of categories, where the unique identifier called uid, and you want to make that list distinct,

var practiceAreas = from teamMember in AllTeamMembers
from teamMemberRelation in teamMember.TeamToTeamPracticeAreaRecords
select teamMemberRelation.TeamPracticeArea;
temp = practiceAreas.GroupBy(p => p.EntityId).Select(g => g.First()).ToList();
var categoryCollection = from item in AllItems
select item.Categories;
now make it distinct
var distinctCategoryCollection = categoryCollection .GroupBy(p => p.uid).Select(g => g.First())
neat ha ?
Posted in ASP.NET, c#, linq

Leave a Comment