计算数组中数据的出现 [英] Count occurence of data in array

查看:98
本文介绍了计算数组中数据的出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数组:

I have an array like this:

OptiPlex 790
Precision WorkStation T7500
Precision WorkStation T7400
Precision T1500
Precision WorkStation T3500
CELSIUS R650
VMware Virtual Platform
Precision T1500
OptiPlex GX620

我想获取数组的计数并将其添加到新数组中.

I want to get the count of array and will add that in new array.

Element:Count
OptiPlex 790 1 
Precision WorkStation T7500 1 
Precision WorkStation T7500 1

我想将此值存储在新数组中.因此,我将在以后/其他地方使用它.

I want to store this value in new array. So, i will use it later/somewhere else.

$array = @()
for ($i=1; $i -le $rowMax-1; $i++) {
    $Model = $sheet.Cells.Item($rowModel+$i, $colModel).text
    Write-Host ("I am reading data on row: " + $i)
    $array += $Model
}

$array | Group

目前,上述脚本可以正常工作,但是我不知道如何将这些数据添加到新数组中.

At the moment above script is working fine but I don't know how I can add this data to new array.

推荐答案

我将构造一个哈希表而不是数组:

I would construct a hash table rather than an array:

$Models = @(
  'OptiPlex 790'
  'Precision WorkStation T7500'
  'Precision WorkStation T7400'
  'Precision T1500'
  'Precision WorkStation T3500'
  'CELSIUS R650'
  'VMware Virtual Platform'
  'Precision T1500'
  'OptiPlex GX620'
)

# Create a hashtable
$ModelCount = @{}

# Iterate over each entry in the array, increment value count in hashtable
$Models |ForEach-Object { $ModelCount[$_]++ }

现在,您的哈希表可以计算出您需要的所有信息:

Now your hash table countains all the information you need:

PS C:\> $ModelCount

Name                           Value
----                           -----
OptiPlex 790                   1
VMware Virtual Platform        1
Precision WorkStation T7500    1
Precision T1500                2
CELSIUS R650                   1
Precision WorkStation T7400    1
OptiPlex GX620                 1
Precision WorkStation T3500    1

您可以轻松添加新值:

# Let's say you found another 3 OptiPlex GX620 somewhere:
$ModelCount['OptiPlex GX620'] += 3

和条目:

$ModelCount['New Model']++

您仍然可以对其进行迭代:

And you can still iterate over it:

PS C:\> $ModelCount.Keys |Sort-Object |ForEach-Object {
>>>     Write-Host "We have $($ModelCount[$_]) of $_ in stock"
>>> }
We have 1 of CELSIUS R650 in stock
We have 1 of OptiPlex 790 in stock
We have 4 of OptiPlex GX620 in stock
We have 2 of Precision T1500 in stock
We have 1 of Precision WorkStation T3500 in stock
We have 1 of Precision WorkStation T7400 in stock
We have 1 of Precision WorkStation T7500 in stock
We have 1 of VMware Virtual Platform in stock

这篇关于计算数组中数据的出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆