DotNet 笔记

东方欲晓,莫道君起早。

C#对list内元素的位置进行调动

/*

    功能说明: 移动list内元素的位置
    计算机名:SZCB
    创建日期:2017/6/26 10:34:44
    作    者:zhifeiya
    版 本 号:v-1.00
	
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LkTiKu.Util
{
    public static partial class ListMove
    {
        /// <summary>
        /// KKMoveUps the specified data list.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dataList">The 数据列表 list.</param>
        /// <param name="id">需要Move的下标(当前被移动元素所在的位置),如:1,2,4,5,6...</param>
        /// <param name="Step">Move的 Step. 默认为1</param>
        /// <returns></returns>
        public static bool kkMoveUp<T>(this IList<T> dataList, int id, int Step = 1)
        {
            return dataList.kkMove(id, id - Step);
        }

        public static bool kkMoveDown<T>(this IList<T> dataList, int id, int Step = 1)
        {
            return dataList.kkMove(id, id + Step);
        }

        public static bool kkMoveTop<T>(this IList<T> dataList, int id)
        {
            return dataList.kkMove(id, 0);
        }

        public static bool kkMoveBottom<T>(this IList<T> dataList, int id)
        {
            return dataList.kkMove(id, dataList.Count - 1);
        }

        public static bool kkMove<T>(this IList<T> dataList, int OldID, int NewID)
        {
            if (OldID >= dataList.Count || NewID >= dataList.Count || OldID < 0 || NewID < 0 || OldID == NewID) { return false; }

            try
            {
                var sel = dataList[OldID];
                dataList.RemoveAt(OldID);
                dataList.Insert(NewID, sel);
                return true;
            }
            catch (Exception)
            {
                return false; ;
            }

        }
        public static bool kkExchange<T>(this IList<T> list, int OldID, int NewID)
        {
            if (OldID >= list.Count || NewID >= list.Count || OldID < 0 || NewID < 0 || OldID == NewID) { return false; }

            try
            {
                var sel = list[OldID];
                list[OldID] = list[NewID];
                list[NewID] = sel;
                return true;
            }
            catch (Exception)
            {
                return false; ;
            }


        }
    }
}

 

Loading