C#把数组中的某个元素取出来放到第一个位置

如何取出数组中符合某种条件的元素,然后放在数组最前面,即索引为0的位置?

 

思路大致如下:
→找到符合条件的数组元素,把之赋值给一个临时变量temp,并记下该数组元素的索引位置,假设是index
→在源数组中,从索引为0的数组元素开始,拷贝index个数组元素到另外一个目标数组
→把临时变量temp赋值给目标数组索引为0的位置


    public static class ArrHelper
    {
        /// <summary>
        /// 对类型为T的数组进行扩展,把满足条件的元素移动到数组的最前面
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="arr">源数组</param>
        /// <param name="match">lamda表达式</param>
        /// <returns></returns>
        public static bool MoveToFront<T>(this T[] arr, Predicate<T> match)
        {
            //如果数组的长度为0
            if (arr.Length == 0)
            {
                return false;
            }
            //获取满足条件的数组元素的索引
            var index = Array.FindIndex(arr, match);
            //如果没有找到满足条件的数组元素
            if (index == -1)
            {
                return false;
            }
            //把满足条件的数组元素赋值给临时变量
            var temp = arr[index];
            Array.Copy(arr, 0, arr, 1, index);
            arr[0] = temp;
            return true;
        }
        public static void PrintArray<T>(T[] arr)
        {
            foreach (var item in arr)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
        }
    }

 

以上,是针对泛型数组的扩展,所以可以直接使用数组实例调用扩展方法。

    class Program
    {
        static void Main(string[] args)
        {
            int[] intArr = new int[]{1, 2, 3, 4, 5};
            ArrHelper.PrintArray(intArr);
            intArr.MoveToFront(i => i == 3);
            ArrHelper.PrintArray(intArr);
            Console.ReadKey();
        }
    } 
原文地址:https://www.cnblogs.com/darrenji/p/4138265.html