linq query to return distinct field values from a list of objects

前端 未结 7 1620
醉梦人生
醉梦人生 2020-12-24 11:42
class obj
{
    int typeId; //10 types  0-9 
    string uniqueString; //this is unique
}

Assume there is list with 100 elements of obj, but only 10

相关标签:
7条回答
  • 2020-12-24 12:10

    Assuming you want the full object, but only want to deal with distinctness by typeID, there's nothing built into LINQ to make this easy. (If you just want the typeID values, it's easy - project to that with Select and then use the normal Distinct call.)

    In MoreLINQ we have the DistinctBy operator which you could use:

    var distinct = list.DistinctBy(x => x.typeID);
    

    This only works for LINQ to Objects though.

    You can use a grouping or a lookup, it's just somewhat annoying and inefficient:

    var distinct = list.GroupBy(x => x.typeID, (key, group) => group.First());
    
    0 讨论(0)
提交回复
热议问题