Ben Fisher Ben Fisher - 1 year ago 247 Question

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

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


Class Hardware has the following Properties:

  • ModelName

  • Status

  • CPUStatus

  • MemoryStatus

  • DiskStatus

The List is populated by reading a CSV file, once it's populated, I want to return the distinct records based on the ModelName

I've attempted by doing it as follows:

(From a In HWModels Select a.ModelName).Distinct

But this isn't right because I end up with a list of only the ModelName's and nothing else.

How do I get the Distinct function to return all of the other class members within the list?

Answer Source

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 :(