繁体   English   中英

如何在C#中创建链接数组列表

[英]How to create Linked Array List in C#

我需要创建一个具有链接列表容量的数组。

基本上,我需要一个基于静态索引的列表(如数组),但有可能获取下一个和上一个字段(并轻松地在列表中来回循环和前进,就像使用链接列表一样)。 注意:数组是二维的。 我使用自定义类作为数组值。 因此,我可以为每个实例设置上一个和下一个属性。

有内置的C#集合吗? 如果没有,关于如何创建此版本的任何简单建议? (我已经有一个版本,由2种方法组成。一种方法向前循环以设置前一个字段,而另一种方法向后循环以设置下一个字段,但仍然很麻烦。)

提前致谢

编辑:

问题是我对二维数组的使用。 如果遍历我的数组:

            for (byte x = 0; x < Grid.GetLength(0); x++) 
            {
                for (byte y = 0; y < Grid.GetLength(1); y++) /
                {
                    //At certain point, I need to get the previous field. I can do:
                    if (y != 0)
                    {
                        y -= 2; //-2 because I will y++ in for. Already getting messy
                    }
                    else 
                    {
//What if y == 0? Then I can't do y--. I should get max y and  do x-- to get previous element:

                        y = (byte)(Grid.GetLength(1) - 1); //to get max value y

                        x--;
                    }
}
    }

有一个内置的LinkedList<T>类。

但是从您的描述来看,为什么数组不起作用? 它是静态的,基于索引,您可以通过增加/减少索引来轻松获取下一个和上一个元素。 很难从代码中确切地看到您需要什么,但是我想指出,您可以使用以下方法轻松枚举多维数组:

var arry = new int[2,3];
foreach(var item in arry)
{
    ...
}

因此,您可以将其与Stack<T>结构结合(将项目推入堆栈,然后将其弹出以获得上一个)。

或者,您可以将数组直接转换为LinkedList

var list = new LinkedList(arry.Cast<int>()); // flattens array

或者,要保留原始数组中的索引并仍将值作为链接列表循环遍历,请使用:

var list = new LinkedList(arry.Cast<int>.Select((item, i) => new 
{ 
    Item = item, 
    Index1 = i % arry.GetLength(1), 
    Index2 = i / arry.GetLength(0) 
}));
var node = list.First;
while(node.Next != null)
{
    Console.WriteLine("Value @ {1}, {2}: {0}", node.Value.Item, node.Value.Index1, node.Value.Index2);
    // on some condition move to previous node
    if (...)
    {
        node = node.Previous;
    }
    else
    {
        node = node.Next;
    }
}

不,你没有。 与其代替传统阵列代替“智能链接节点阵列”(您正在朝着这个方向发展),不如尝试在循环主体中添加几个变量:

byte x_len = Grid.GetLength(0);
byte y_len = Grid.GetLength(1);
byte prev_x, next_x, prev_y, next_y;

for (byte x = 0; x < x_len; ++x) 
{
  prev_x = x == 0? x_len - 1 : x - 1;
  next_x = x == x_len - 1? 0 : x + 1;
  for (byte y = 0; y < y_len; ++y)
  {
    prev_y = y == 0? y_len - 1 : y - 1;
    next_y = y == y_len - 1? 0 : y + 1;

    // here, you have access to the next and previous
    // in both directions, satisfying your requirements
    // without confusing your loop variables.

  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM