Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...