Linq query to get the distinct values in a list

You can use the following code:

List<Member> sourceList = new List<Member>();
IEnumerable<Member> result = 
    (sourceList as IEnumerable<Member>)
    .Distinct()
    .OrderBy(value => value.CategoryId);

This is similar to those above, however it is technically a one liner for those interested....

var queryResult= (from l in list
                  select new Member()
                 { 
                    CategoryId = l.CategoryId , 
                    MemberName = l.MemberName 
                    Distance = l.Distance
                 }).GroupBy(x=>x.CatagoryId).Select(z=>z.OrderBy(i=>i.Distance).First()).ToList();

This should cover your needs:

var grouped = list.GroupBy(item => item.CategoryId);
var shortest = grouped.Select(grp => grp.OrderBy(item => item.Distance).First());

It first groups the items with the same CategoryId, then selects the first from each group (ordered by Distance).


Update: You could chain all of these together too, if you prefer:

var shortest = list.GroupBy(item => item.CategoryId)
                   .Select(grp => grp.OrderBy(item => item.Distance)
                   .First());

Group the list into categories, then order each grouping by distance, taking the first item (the lowest distance). Project the results into a new Member collection.

var query = from member in list 
            group member by member.CategoryId into memberGrouping
            let groupedMember = memberGrouping.OrderBy (mg => mg.Distance).First() 
            select new Member()
            { 
              CategoryId = memberGrouping.Key, 
              MemberName = groupedMember.MemberName, 
              Distance = groupedMember.Distance 
            };

Tags:

C#

Linq

C# 4.0