【问题标题】:EF Core and Collection ordering by specified column: move up and downEF Core 和 Collection 按指定列排序:上下移动
【发布时间】:2018-05-17 01:58:38
【问题描述】:

在集合中实现排序的最佳方式是什么? 需要支持move upmove 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; }
}

【问题讨论】:

  • 你使用过OrderBy扩展方法吗?
  • 嗯,这个问题缺少各种必需的细节。一方面,与 EF 的关系并不清楚,而且您没有显示任何代码来告诉我们您希望在何处/如何具体地上下移动项目,以及您(显然)是如何陷入此过程的。
  • 在这里。用于.OrderBy(o =&gt; o.Priority)的属性位置
  • 我清楚地知道如何移动。但想知道 EF 中是否有任何内置解决方案或 EF 的最佳实践。我已经手动完成了,但我不想再制造一辆自行车 :)

标签: entity-framework entity-framework-core ef-core-2.0


【解决方案1】:

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

希望对你有帮助。

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

    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-18
    • 2017-05-22
    • 2022-08-02
    • 2018-04-05
    • 1970-01-01
    • 2011-02-26
    • 2020-12-01
    • 2020-10-05
    相关资源
    最近更新 更多