Cómo obtener valores distintos de la lista (de T) usando Linq

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

Class Hardware has the following Properties:

  • Nombre del modelo
  • Estado
  • 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?

preguntado el 10 de marzo de 12 a las 09:03

2 Respuestas

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 MásLINQ proporciona una 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 :(

Respondido el 25 de Septiembre de 19 a las 03:09

MoreLINQ library Google Code link is dead - Chad

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

Respondido el 10 de junio de 16 a las 15:06

this is an easy way to do what i needed, thanks Panteli - dimitris tomás

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.