在进行列表排序时,有个“上移”和“下移”操作,这个一般在内存里完成,然后统一提交到数据库中,对于上移与下移的设计,大叔在LIND.DDD.DOMAIN里有一个ISortBehavor接口,主要是说,如果实体对象支持排序功能,可以实现这个接口,而在扩展库中,将有为本地结果集动态排序(上移和下移)的方法,这个设计类似于ABP项目里的软删除,当然在大叔LIND里也有对删除的逻辑操作。
ISortBehavor内容
class Entity { public int ID{ get; set; } } interface ISortBehavor { int SortNumber{ get; set; } }
而上移与下移我们使用一个泛型方法来接收参数,这样扩展性更好一些,开发人员只要把需要上下移的集合传到方法里,之后你的集合就可以被排序,当然这里面会进行各个元素的移动操作!
class Extenstion { /// <summary> /// Sortable the specified list, id and newSort. /// </summary> /// <param name=‘list‘> /// List. /// </param> /// <param name=‘id‘> /// Identifier. /// </param> /// <param name=‘newSort‘> /// New sort. /// </param> /// <typeparam name=‘T‘> /// The 1st type parameter. /// </typeparam> public static void Sortable<T> (List<T> list, int id, int newSort) where T:class { var old = list.Find (i => (i as Entity).ID == id); if (old == null || (old as ISortBehavor).SortNumber == newSort) return; if ((old as ISortBehavor).SortNumber > newSort) { (old as ISortBehavor).SortNumber = newSort; foreach (ISortBehavor item in list.FindAll(i=>(i as Entity).ID!=id && (i as ISortBehavor).SortNumber>=newSort)) { item.SortNumber += 1; } } else { (old as ISortBehavor).SortNumber = newSort; foreach (ISortBehavor item in list.FindAll(i=>(i as Entity).ID!=id && (i as ISortBehavor).SortNumber<=newSort)) { item.SortNumber -= 1; } } list.ForEach (i => { Console.WriteLine ((i as Entity).ID + "sort:" + (i as ISortBehavor).SortNumber); } ); } }
我们测试一下程序,看一下神奇的结果
class MainClass { public static void Main (string[] args) { List<Person> list = new List<Person> (); list.Add (new Person {ID=1,Name="zzl",SortNumber=1}); list.Add (new Person {ID=2,Name="zzl2",SortNumber=2}); list.Add (new Person {ID=3,Name="zzl3",SortNumber=3}); Console.WriteLine ("Hello World!"); Extenstion.Sortable (list, 1, 2); Extenstion.Sortable (list, 2, 3); } }
感谢各位中秋阅读!
时间: 2024-11-12 00:09:54