创建一个包含两列值的VB.NET数组?

时间:2011-04-11 12:45:08

标签: asp.net vb.net arrays variables

我知道如何创建一个数组并正常循环 - 但是如果我需要一个多列数组怎么办?例如通常我可以这样做:

For Each row in NameofArray
  Dim name as String = row
  Response.Write("Hello " & name & "!")
Next

但是,如果我想做类似的事情呢?

For Each row in NameofArray
   Dim name as String = row.name
   Dim age as Integer = row.age
   Response.Write("Hello " & name & "! You are " & age & " years old!"
Next

如果数组无法做到这一点,还有另一种方法可以实现吗?

5 个答案:

答案 0 :(得分:4)

创建自定义数据类型:

 public struct DataType 
    public string Name; 
    public int Age; 
 }

你可以在类似的数组中使用这种类型:

 DataType[] myData = new DataType[100]; 
 myData[0].Name = "myName"; 
 myData[0].Age = 100; 

注意,如果通过foreach循环遍历该数组,则每次迭代返回的元素都不会被更改。如果这是您的要求,请考虑在上面的DataType声明中使用“class”而不是“struct”。这将带来一些其他含义。例如,类DataType的实例将明确地通过'new'关键字创建。

答案 1 :(得分:2)

在阅读你的评论之后,我认为我的另一个答案可能就是你要找的。

什么类型的行和NameOfArray是什么类型的?

如果您希望将行放入具有多个成员的coumpound类型,那么有几个选项。

Structure Row
   Public Name as String
   Public Age as Integer
End Structure
例如

。如果您希望将引用类型替换Class替换Structure

或使用匿名类型

Dim row = New With {Name = "Bob", Age = 21}

然后,您可以使用泛型来创建可以使用ForEach进行迭代的行列表。

Dim NameOfList As System.Collections.Generic.List(of Row)

或者它是否是支持

的LINQ查询的结果
IEnumerable(of New With{Name As String, Age As Int}). //Not sure if this is VB

我不确定我是否理解你的问题,并希望这是你想要的那种。

正如你从我的回答者那里看到的,对C#匿名类型的支持是优越的,但是,自从你在VB.Net中提出这个问题后,我将自己局限于这种情况。

答案 2 :(得分:1)

您是否尝试过Dictionary Class。您可以使用KeyValue对类循环遍历Dictionary。

// Create a new dictionary of strings, with string keys.
//
Dictionary<string, string> openWith = 
    new Dictionary<string, string>();

// Add some elements to the dictionary. There are no 
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");


foreach(var item in openWith)
{
Console.WriteLine(item.Key +" can be open with " + item.value);
}

答案 3 :(得分:1)

你需要(可以)使用两个维度索引到你的数组,即......

Dim array(,) As Object = { _
     {"John",26}, _
     {"Mark",4} _
}

For row As Integer = 0 to array.GetUpperBound(0)
   Dim name as String = CStr(array(row,0))
   Dim age as Integer = CInt(array(row,1))
   Response.Write("Hello " & name & "! You are " & age & " years old!")
Next

尽管将这类信息存储在类或用户定义的某种类型中会更好。

答案 4 :(得分:1)

在阅读你的评论后,我想我理解了这个问题。

你可以做到

///Spacer Top
Dim NameOfArray = {New With {.Age = 21, .Name = "Bob"}, New With {.Age = 74, .Name = "Gramps"}}
///Spacer Bottom

如果你想创建一个IEnumberable匿名类型的Name Age元组;-p

相关问题