如何使用Linq从List(Of T)中获得不同的值 [英] How to get Distinct Values from List(Of T) using Linq
问题描述
我有一个(硬件)列表-该列表称为HWModels
I have a List(Of Hardware) - the List is called HWModels
Class Hardware具有以下属性:
Class Hardware has the following Properties:
- ModelName
- 状态
- CPUStatus
- MemoryStatus
- DiskStatus
通过读取CSV文件填充列表,填充后,我想基于ModelName返回不同的记录
The List is populated by reading a CSV file, once it's populated, I want to return the distinct records based on the ModelName
我尝试如下进行操作:
(From a In HWModels Select a.ModelName).Distinct
但这是不对的,因为我最终仅得到了ModelName的列表,而没有其他内容.
But this isn't right because I end up with a list of only the ModelName's and nothing else.
如何获取Distinct函数以返回列表中的所有其他类成员?
How do I get the Distinct function to return all of the other class members within the list?
推荐答案
LINQ to Objects不能提供任何功能来整齐地与投影区分开".您可以按名称分组,然后取每组中的第一个元素,但这很丑陋.
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.
我的 MoreLINQ 提供了
My MoreLINQ provides a DistinctBy
method though - in C# you'd use:
var distinct = HWModels.DistinctBy(x => x.ModelName).ToList();
大概是VB就像
Dim distinct = HWModels.DistinctBy(Function(x) x.ModelName).ToList
对于任何语法错误的歉意:(
Apologies for any syntax errors though :(
这篇关于如何使用Linq从List(Of T)中获得不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!