Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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?

like image 368
Ben Fisher Avatar asked Mar 10 '12 09:03

Ben Fisher


People also ask

How to get Distinct values in LINQ query?

C# Linq Distinct() method removes the duplicate elements from a sequence (list) and returns the distinct elements from a single data source. It comes under the Set operators' category in LINQ query operators, and the method works the same way as the DISTINCT directive in Structured Query Language (SQL).

How do I get distinct values from a list?

Using Python's import numpy, the unique elements in the array are also obtained. In the first step convert the list to x=numpy. array(list) and then use numpy. unique(x) function to get the unique values from the list.


2 Answers

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

like image 100
Jon Skeet Avatar answered Oct 11 '22 18:10

Jon Skeet


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
like image 45
pantelis Avatar answered Oct 11 '22 19:10

pantelis