VB.net在数组中存储列表时出错

时间:2014-11-27 14:11:20

标签: vb.net list

我有以下代码,它的目标是获取一个初始列表并获取列表中的每个元素并将其存储在一个列表数组中,每个列表都在数组中,将每个元素保存在自己的列表中。例如

The list 2, 2, 3, 3, 3, 3, 5, 5, 7, 9, 9. Would create five lists:
List 1: 2, 2
List 2: 3, 3, 3, 3, 
List 3: 5, 5
list 4: 7
List 5: 9, 9

这是我目前的代码: -

 Dim cnt As Integer = 0
        Dim lists(uniqueFactors.Count) As List(Of Integer)
        Dim saver As Integer = factors.Item(0)
        Console.WriteLine(saver)
        For Each i In factors
            lists(cnt).Add(i)
            If saver <> i Then
                cnt = cnt + 1
            End If
            saver = i
        Next

提前全部谢谢!

2 个答案:

答案 0 :(得分:0)

为什么不使用这样的列表列表?

    Dim last As Integer
    Dim first As Boolean = True
    Dim ints As List(Of Integer)
    Dim lists As New List(Of List(Of Integer))
    For Each i In factors
        If first Then
            first = False
            ints = New List(Of Integer)
            ints.Add(i)
            lists.Add(ints)
            last = i
        ElseIf i = last Then
            ints.Add(i)
        Else
            ints = New List(Of Integer)
            ints.Add(i)
            lists.Add(ints)
            last = i
        End If
    Next

答案 1 :(得分:0)

使用Dictonary<TKey, TValue>可能会更好。

Dim storage As New Dictionary(Of Integer, Integer)

'      Number  Occurrences
'           |  |
storage.Add(2, 2)
storage.Add(3, 4)
storage.Add(5, 2)
storage.Add(7, 1)
storage.Add(9, 2)

您可以像这样迭代列表:

For Each item As KeyValuePair(Of Integer, Integer) In storage
    Dim number As Integer = item.Key
    Dim occurrences As Integer = item.Value
Next

获取给定数字的出现次数,如下所示:

Dim number As Integer = 9
Dim occurrences As Integer = storage(number) 'Return: 2

更改出现次数:

storage.Item(number) = 4 'Set to 4
storage.Item(number) += 1 'Increase from 2 to 3
storage.Item(number) -= 1 'Decrease from 2 to 1

为给定数字创建枚举数,数组和/或事件列表:

Dim iterator As IEnumerable(Of Integer) = Enumerable.Repeat(number, occurrences).ToList()
Dim array As Integer() = Enumerable.Repeat(number, occurrences).ToArray()
Dim list As List(Of Integer) = Enumerable.Repeat(number, occurrences).ToList()

您还可以编写扩展方法:

Public Module Extensions

    <System.Runtime.CompilerServices.Extension()>
    Public Function ToList(Of TKey)(source As Dictionary(Of TKey, Integer), key As TKey) As List(Of TKey)
        Return Enumerable.Repeat(key, source.Item(key)).ToList()
    End Function

End Module

现在只需编写:

即可创建列表
Dim occurrences As List(Of Integer) = storage.ToList(number)
相关问题