如何在csv中的哈希表中为一个键具有多个值 [英] How to have multiple values for one key in hashtable from csv
问题描述
我试图创建一个空的哈希表,导入CSV,按ID将事物分组,然后将每个组添加到哈希表中。
I tried to create an empty hashtable, import your CSV, group things by ID, then add each group to the hashtable.
但是由于某些原因,我遇到了错误:
But for some reason I am getting error:
Exception calling "Add" with "2" argument(s): "Key cannot be null.
Parameter name: key"
At line:4 char:5
+ $myHT.add($_.Name,$_.Group.Name)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentNullException
我有然后尝试以下更接近我期望的输出的内容:
I have then tried the following which is much closer to my desired output:
$myCSV = Import-Csv "X:\Path\To\My\CSV\File.csv"
$myCSV | Group-Object -Property ID | Select-Object -Property @{N="ID";E={$_.Name}},@{N="Name";E={$_.Group.Name -join ","}}
但是,如果我在csv中具有相同的名称和相同的ID,是否仍然存在重复项。无论如何,只有唯一的名称吗?
我目前得到以下信息:
However, if I still have duplicates if I have the same name with the same ID in my csv. Is there anyway to get unique names only? I currently get the following:
ID Name
1234 John, John, Jeff
1235 Jane
1236 Bob
我只希望名称已经存在一次。
I only want the name to be added once if it already exists.
推荐答案
如果您想要一个哈希表,那么最简单的方法是制作一个空表,导入CSV并进行分组按ID,然后将每个组添加到哈希表。
If you want a hashtable, then the easiest way would be to make an empty one, import your CSV, group things by ID, then add each group to the hashtable.
$myHT = @{}
$myCSV = Import-Csv "X:\Path\To\My\CSV\File.csv"
$myCSV | Group ID | ForEach-Object {
$myHT.add($_.Name,$_.Group.Name)
}
这不会在名称之间放置漂亮的',',但是哈希表中的每个键的值都是名称数组。
That won't put a pretty ', ' between names, but each key in the hashtable will have a value that's an array of names.
这篇关于如何在csv中的哈希表中为一个键具有多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!