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});
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.
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).
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.
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.
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
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With