Linq query to get the distinct values in a list

后端 未结 7 1735
攒了一身酷
攒了一身酷 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:02

    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();
    
    0 讨论(0)
  • 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());
    
    0 讨论(0)
  • 2021-02-08 23:11

    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 
                };
    
    0 讨论(0)
  • 2021-02-08 23:19

    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());
    
    0 讨论(0)
  • 2021-02-08 23:21

    You can use the following code:

    List<Member> sourceList = new List<Member>();
    IEnumerable<Member> result = 
        (sourceList as IEnumerable<Member>)
        .Distinct()
        .OrderBy(value => value.CategoryId);
    
    0 讨论(0)
  • 2021-02-08 23:21

    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);
    
    0 讨论(0)
提交回复
热议问题