是否可以比较System.Collection.Arraylist中的元素以查看是否有任何元素相同?

时间:2016-01-20 01:56:11

标签: arraylist vbscript iteration

基本上问题的标题是什么。如果我提示用户输入他们的名字,那么请用户输入任意5个号码,最后将答案存入arraylist。

Wscript.StdOut.WriteLine "What is your name"
name = Wscript.StdIn.ReadLine
Wscript.StdOut.WriteLine "Enter any number"
att1 = CInt(WScript.StdIn.ReadLine)
Wscript.StdOut.WriteLine "Enter any number"
att2 = Cint(Wscript.StdIn.ReadLine)
Wscript.StdOut.WriteLine "Enter any number: "
att3 = CInt(Wscript.StdIn.ReadLine)
Wscript.StdOut.WriteLine "Enter any number: "
att4 = CInt(Wscript.StdIn.ReadLine)
Wscript.StdOut.WriteLine "Enter any number: "
att5 = CInt(Wscript.StdIn.ReadLine)

set myNumArray =  CreateObject("System.Collections.Arraylist")

myNumArray.Add att1
myNumArray.Add att2
myNumArray.Add att3
myNumArray.Add att4
myNumArray.Add att5

我怎样才能发现用户返回的任何数字是否相同。

例如,用户输入5个数字:1,2,2,4,5。如何判断用户是否输入了两次?

2 个答案:

答案 0 :(得分:0)

使用字典

Set Arg = WScript.Arguments
set WshShell = createObject("Wscript.Shell")
Set Inp = WScript.Stdin
Set Outp = Wscript.Stdout

    Set Dict = CreateObject("Scripting.Dictionary")
    Do Until Inp.AtEndOfStream
        On Error Resume Next
        Line=Inp.readline
        Dict.Add Line, ""
        If Err.Number <> 0 then
            If LCase(Arg(1)) = "l" then
                Dict.Remove Line
                Dict.Add Line, ""
            End If
        End If
    Loop
    For Each thing in Dict.Keys()
        Outp.writeline thing
    Next

<强>去重

filter dedup {f|l}
filter dup {f|l}

删除文件中的重复行,保留第一个或最后一个

f - keeps the first occuring duplicate line
c - keeps the last occuring duplicate line

示例

filter dedup f < "%systemroot%\win.ini"

仅对标准输入和标准输出进行读写。这些仅在命令提示符中可用。

filter <inputfile >outputfile
filter <inputfile | other_command
other_command | filter >outputfile
other_command | filter | other_command

答案 1 :(得分:0)

使用字典( 正确):

Option Explicit

Dim alInp : Set alInp = CreateObject("System.Collections.ArrayList")
alInp.Add 1
alInp.Add 2
alInp.Add 2
alInp.Add 4
alInp.Add 5

Dim dicInp : Set dicInp = CreateObject("Scripting.Dictionary")
Dim elm
For Each elm In alInp
    dicInp(elm) = dicInp(elm) + 1
Next
Dim key
For Each key In dicInp
    If dicInp(key) > 1 Then WScript.Echo "found", key, dicInp(key), "times"
Next

输出中:

cscript 34890229.vbs
found 2 2 times

- 使用.Contains方法查看ArrayList的当前内容:

Option Explicit

Dim alInp : Set alInp = CreateObject("System.Collections.ArrayList")
Dim elm
For Each elm In Array(1, 2, 2, 4, 5)
    If alInp.Contains(elm) Then
       WScript.Echo "not again:", elm
    Else
       alInp.Add elm
    End If
Next
WScript.Echo Join(alInp.ToArray())

输出:

cscript 34890229-2.vbs
not again: 2
1 2 4 5