Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq query to get the distinct values in a list

Tags:

c#

linq

c#-4.0

Suppose this is my member class

class Member 
{
    public string CategoryId { get; set; }
    public string MemberName { get; set; }
    public int Distance { get; set; }
}

And, this is list.

var list = new List<Member>();
list.Add(new { CategoryId = "01", MemberName="andy" Distance=3});
list.Add(new { CategoryId = "02", MemberName="john" Distance=5});
list.Add(new { CategoryId = "01", MemberName="mathew" Distance=7});
list.Add(new { CategoryId = "03", MemberName="bakara" Distance=2});

Can anyone please suggest the logic/ linq query to get the List having distinct/unique categoryID with Shortest distance.

The output should be :

list.Add(new { CategoryId = "01", MemberName="andy" Distance=3});
list.Add(new { CategoryId = "02", MemberName="john" Distance=5});
list.Add(new { CategoryId = "03", MemberName="bakara" Distance=2});
like image 333
PaRsH Avatar asked Jan 02 '14 13:01

PaRsH


People also ask

How do I select distinct values in LINQ query?

If you need to have distinct values in the list, you can use various ways to achieve the desired result. LINQ has Distinct() function which provides the unique list of values from a single data source.

How do I get distinct on a single column in LINQ?

distinct in Linq to get result based on one field of the table (so do not require a whole duplicated records from table). I know writing basic query using distinct as followed: var query = (from r in table1 orderby r. Text select r).

How does distinct work in LINQ?

LINQ Distinct operator removes all the duplicate values from the collection and finally returns the dissimilar or unique values. The LINQ Distinct operator available in only Method Syntax and it not supports the Query Syntax. LINQ Distinct is an operator which comes under Set Operator.

Why distinct is not working in LINQ?

LINQ Distinct is not that smart when it comes to custom objects. All it does is look at your list and see that it has two different objects (it doesn't care that they have the same values for the member fields). One workaround is to implement the IEquatable interface as shown here.


1 Answers

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 
            };
like image 60
asawyer Avatar answered Oct 04 '22 00:10

asawyer