根据序列更改数组

时间:2015-04-25 06:46:25

标签: c# arrays

我有一些Image滑块,我想更改图像滑块的顺序。当前序列是从数据库字段设置的(从数据库中获取序列号集并显示它)。

现在,我想更改序号。让我们说,
我的滑块序列为1, 2, 3, 4, 5, 6, 7, 8, 9, 10&我需要将第4个位置滑块更改为第8个位置,然后我的滑块编号序列为1, 2, 3, 5, 6, 7, 4, 8, 9, 10

这是一张易于理解的图像 CLICK HERE http://i62.tinypic.com/30dl1qb.png

我有一个带有当前序列的int数组,

int[] currentSequence = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

mycode的:

int[] currentSequence = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var currentPosition = iproductrepositroy.GetSingle(x => x.ProductName.Equals(ProductName)).ProductSequence;// 4th position
var expectedPosition = ChangeSequence;// 8th position

if (currentPosition < expectedPosition)//right shift -->
{
    int i = 0;
    for (i = (int)currentPosition + 1; i < expectedPosition; i++)
    {
        // I wanted to know how to change the above array here
    }
}
else//left shift <--
{
    int i;
    for (i = (int)currentPosition - 1; i > expectedPosition; i--)
    {

    }
}

2 个答案:

答案 0 :(得分:4)

您可以更轻松地在列表中执行此操作:

class Program
{
    static void Main(string[] args)
    {
        int currentPosition = 3;
        int expectedPosition = 7;

        int adjust = (currentPosition < expectedPosition) ? 1 : 0;
        List<int> list = new List<int> { 1,2,3,4,5,6,7,8,9,10};
        var item = list[currentPosition];
        list.RemoveAt(currentPosition);
        list.Insert(expectedPosition - adjust , item); //Insert position may be one less at the moment, so use calculated adjustment

        foreach (int i in list)
        {
            Console.WriteLine(i.ToString());
        }
        var discard = Console.ReadKey();
    }
}

答案 1 :(得分:1)

除非我误解了您的要求,否则这是进行重新排序的最简单方法:

var currentSequence = new [] { 1,2,3,4,5,6,7,8,9,10 };
var reordering = new [] { 1,2,3,5,6,7,4,8,9,10 };

var reorderedSequence =
    reordering
        .Select(r => currentSequence[r - 1])
        .ToArray();

要证明这是有效的,请尝试使用它:

var currentSequence = new [] { "A","B","C","D","E","F","G","H","I","J" };

回馈:

{ "A", "B", "C", "E", "F", "G", "D", "H", "I", "J" }