zoukankan      html  css  js  c++  java
  • 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();
    
            }
    
        } 
    
  • 相关阅读:
    nginx能访问html静态文件但无法访问php文件
    LeetCode "498. Diagonal Traverse"
    LeetCode "Teemo Attacking"
    LeetCode "501. Find Mode in Binary Search Tree"
    LeetCode "483. Smallest Good Base" !!
    LeetCode "467. Unique Substrings in Wraparound String" !!
    LeetCode "437. Path Sum III"
    LeetCode "454. 4Sum II"
    LeetCode "445. Add Two Numbers II"
    LeetCode "486. Predict the Winner" !!
  • 原文地址:https://www.cnblogs.com/darrenji/p/4138265.html
Copyright © 2011-2022 走看看