【问题标题】:Change array according to the sequence按顺序改变数组
【发布时间】:2019-09-27 15:14:06
【问题描述】:

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

现在,我想更改序列号。可以说,
我的滑块序列是 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 并且我需要将第 4 个位置的滑块更改为第 8 个位置,之后我的滑块编号序列是 1, 2, 3, 5, 6, 7, 4, 8, 9, 10

为了便于理解,这里有一张图片

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

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

我的代码:

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--)
    {

    }
}

【问题讨论】:

    标签: c# arrays


    【解决方案1】:

    这对您来说可能更容易在列表中完成:

    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();
        }
    }
    

    【讨论】:

    • 顺便说一句,从数组到列表来回切换非常容易。您可以从数组构造一个列表(或调用ToList()):List&lt;int&gt; list = new List&lt;int&gt;(currentSequence); 并且您可以将列表转换回数组:list.ToArray();
    【解决方案2】:

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

    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" }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-29
      • 1970-01-01
      • 2019-01-11
      • 1970-01-01
      相关资源
      最近更新 更多