Suppose this is my member class
class Member
{
public string CategoryId { get; set; }
public string MemberName { get; set; }
public int Distance { g
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
};
This also works, if you do not require items ordered by (little modified Kjartan's answer)
var grouped = list.GroupBy(item => item.CategoryId).ToList();
var shortest = grouped.Select(grp => grp.OrderBy(item => item.Distance).First());
You can use the following code:
List<Member> sourceList = new List<Member>();
IEnumerable<Member> result =
(sourceList as IEnumerable<Member>)
.Distinct()
.OrderBy(value => value.CategoryId);
try this
var distinctIds = list.Distinct(item => item.CategoryId).ToList();
var newList = new List<Member>();
foreach(var id in distinctIds){
newList.Add(list.Where(item => item.CategoryId == id).Min(item => item.Distance))
}
newList.OrderBy(item => item.CategoryId);