vb.net 如何使用 Linq 从 List(Of T) 中获取不同的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9645326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get Distinct Values from List(Of T) using Linq
提问by Ben Fisher
I have a List(Of Hardware) - the List is called HWModels
我有一个列表(硬件) - 该列表被称为 HWModels
Class Hardware has the following Properties:
类硬件具有以下属性:
- ModelName
- Status
- CPUStatus
- MemoryStatus
- DiskStatus
- 型号名称
- 地位
- CPU状态
- 内存状态
- 磁盘状态
The List is populated by reading a CSV file, once it's populated, I want to return the distinct records based on the ModelName
该列表是通过读取 CSV 文件填充的,一旦填充,我想根据 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.
但这不对,因为我最终得到的只有 ModelName 的列表,没有其他任何内容。
How do I get the Distinct function to return all of the other class members within the list?
如何让 Distinct 函数返回列表中的所有其他类成员?
回答by Jon Skeet
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.
LINQ to Objects 没有提供任何东西来巧妙地“通过投影区分”。您可以按名称分组,然后取每个组中的第一个元素,但这非常难看。
My MoreLINQprovides a DistinctBy
method though - in C# you'd use:
我的MoreLINQ提供了一种DistinctBy
方法 - 在 C# 中你会使用:
var distinct = HWModels.DistinctBy(x => x.ModelName).ToList();
Presumably the VB would be something like
大概 VB 会是这样的
Dim distinct = HWModels.DistinctBy(Function(x) x.ModelName).ToList
Apologies for any syntax errors though :(
对任何语法错误表示歉意:(
回答by pantelis
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