0

在集合中实现排序的最佳方法是什么?需要支持 和 之类的move up操作move down

public class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Priority { get; set; }
    public List<Item> Items { get; set; }
}
4

1 回答 1

0

这是一个控制台应用程序,它演示了如何向上和向下移动列表的元素。

我希望它对你有帮助。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    public enum MoveDirection
    {
        Up,
        Down
    }

    static class Program
    {
        static void Main(string[] args)
        {
            List<string> MyList = new List<string>
            {
                "Value 1", "Value 2", "Value 3"
            };

            DisplayList(MyList);
            Console.WriteLine("----------------");
            Move(MyList, 1, MoveDirection.Down);
            DisplayList(MyList);
            Console.WriteLine("----------------");
            Move(MyList, 2, MoveDirection.Up);
            DisplayList(MyList);

            Console.ReadLine();
        }


        public static void Move(List<string> list, int iIndexToMove, MoveDirection direction)
        {

            if (direction == MoveDirection.Up && iIndexToMove > 0)
            {
                var old = list[iIndexToMove - 1];
                list[iIndexToMove - 1] = list[iIndexToMove];
                list[iIndexToMove] = old;
            }
            else if(direction == MoveDirection.Down && iIndexToMove < list.Count() - 1)
            {
                var old = list[iIndexToMove + 1];
                list[iIndexToMove + 1] = list[iIndexToMove];
                list[iIndexToMove] = old;
            }
        }

        public static void DisplayList(List<string> list)
        {
            foreach (var item in list)
            {
                Console.WriteLine(item);
            }
        }

    }
}
于 2017-12-03T16:44:03.410 回答