Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

vb.net - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...