How to get Distinct Values from List(Of T) using Linq

后端 未结 2 355
我寻月下人不归
我寻月下人不归 2020-12-18 04:48

I have a List(Of Hardware) - the List is called HWModels

Class Hardware has the following Properties:

  • ModelName
  • Status
  • C
相关标签:
2条回答
  • 2020-12-18 05:14

    LINQ to Objects doesn't provide anything to do "distinct by a projection" neatly. You could group by the name and then take the first element in each group, but that's pretty ugly.

    My MoreLINQ provides a DistinctBy method though - in C# you'd use:

    var distinct = HWModels.DistinctBy(x => x.ModelName).ToList();
    

    Presumably the VB would be something like

    Dim distinct = HWModels.DistinctBy(Function(x) x.ModelName).ToList
    

    Apologies for any syntax errors though :(

    0 讨论(0)
  • 2020-12-18 05:29

    This will group your objects by the preferred property and then will select the first of each one, removing duplicates.

     Dim newlist = HWModels.GroupBy(Function(x) x.ModelName).Select(Function(x) x.First).ToList
    
    0 讨论(0)
提交回复
热议问题