基于其他数组的值从数组中获取值(VB.Net)

基于其他数组的值从数组中获取值(VB.Net),vb.net,arrays,Vb.net,Arrays,假设我有两个数组: Dim RoomName() As String = {(RoomA), (RoomB), (RoomC), (RoomD), (RoomE)} Dim RoomType() As Integer = {1, 2, 2, 2, 1} 我想根据“RoomType”数组的条件从“RoomName”数组中获取一个值。例如,我想得到一个“RoomName”和“RoomType=2”,因此该算法应该随机化数组的索引,使“RoomType”为“2”,并仅从索引“1-3”中获得一个值范

假设我有两个数组:

Dim RoomName() As String = {(RoomA), (RoomB), (RoomC), (RoomD), (RoomE)}
Dim RoomType() As Integer = {1, 2, 2, 2, 1} 
我想根据“RoomType”数组的条件从“RoomName”数组中获取一个值。例如,我想得到一个“RoomName”和“RoomType=2”,因此该算法应该随机化数组的索引,使“RoomType”为“2”,并仅从索引“1-3”中获得一个值范围


有没有任何可能的方法来解决使用数组的问题,或者有没有更好的方法来解决这个问题?非常感谢您的时间:)

注意:下面使用C#编写示例代码,但希望您能够阅读vb.net的意图

一种更简单的方法是使用一个同时包含名称和类型属性的结构/类,例如:

  public class Room
  {
      public string Name { get; set; }
      public int Type { get; set; }

      public Room(string name, int type)
      {
          Name = name;
          Type = type;
      }
  }
然后,给定一组房间,您可以使用简单的linq表达式找到给定类型的房间:

var match = rooms.Where(r => r.Type == 2).Select(r => r.Name).ToList();
然后,您可以从匹配的房间名称集中找到一个随机条目(见下文)

但是,假设您希望使用并行数组,一种方法是从类型数组中查找匹配的索引值,然后查找匹配的名称,然后使用随机函数查找其中一个匹配值

var matchingTypeIndexes = new List<int>();
int matchingTypeIndex = -1;
do
{
  matchingTypeIndex = Array.IndexOf(roomType, 2, matchingTypeIndex + 1);
  if (matchingTypeIndex > -1)
  {
    matchingTypeIndexes.Add(matchingTypeIndex);
  }
} while (matchingTypeIndex > -1);

List<string> matchingRoomNames = matchingTypeIndexes.Select(typeIndex => roomName[typeIndex]).ToList();

嗨,谢谢你的回复。稍加修改后即可工作!:)
var posn = new Random().Next(matchingRoomNames.Count);
Console.WriteLine(matchingRoomNames[posn]);