Linq query to get the distinct values in a list

后端 未结 7 1737
攒了一身酷
攒了一身酷 2021-02-08 22:34

Suppose this is my member class

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


        
7条回答
  •  长情又很酷
    2021-02-08 23:11

    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());
    

提交回复
热议问题