欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

二维数组的方向获取(简单写法)

程序员文章站 2022-04-08 17:10:17
...
class Program
    {
        static void Main(string[] args)
        {
            string[,] array = new string[3, 4];
            for (int r = 0; r < array.GetLength(0); r++)
            {
                for (int c = 0; c < array.GetLength(1); c++)
                {
                    array[r, c] = r.ToString() + c.ToString();
                }
            }
            string[] result = ArrayHelper.GetElement(array, 1, 0, Direction.Right, 6);

        }
    }
/// <summary>
    /// 方向结构
    /// </summary>
    struct Direction
    {
        //自动属性
        /// <summary>
        /// 行索引
        /// </summary>
        public int RIndex { get; set; }
        /// <summary>
        /// 列索引
        /// </summary>
        public int CIndex { get; set; }
        
        //构造函数
        public Direction(int rIndex, int cIndex)
        {
            this.RIndex = rIndex;
            this.CIndex = cIndex;
        }

        //静态属性
        public static Direction Up
        {
            get
            {
                return new Direction(-1, 0);
            }
        }
        public static Direction Down
        {
            get
            {
                return new Direction(1, 0);
            }
        }
        public static Direction Left
        {
            get
            {
                return new Direction(0, -1);
            }
        }
        public static Direction Right
        {
            get
            {
                return new Direction(0, 1);
            }
        }
    }
/// <summary>
    /// 二维数组工具类
    /// </summary>
    static class ArrayHelper
    {
        /// <summary>
        /// 获取二维数组元素
        /// </summary>
        /// <param name="array">二维数组</param>
        /// <param name="rIndex">行索引</param>
        /// <param name="cIndex">列索引</param>
        /// <param name="dir">方向</param>
        /// <param name="count">希望查找的个数</param>
        /// <returns>所有满足条件的元素</returns>
        public static string[] GetElement(string[,] array, int rIndex, int cIndex,Direction dir,int count)
        {
            List<string> result = new List<string>(count);
            for (int i = 0; i < count; i++)
            {
                rIndex += dir.RIndex;
                cIndex += dir.CIndex;
                if (rIndex >= 0 && rIndex < array.GetLength(0) && cIndex >= 0 && cIndex < array.GetLength(1))
                    result.Add(array[rIndex, cIndex]);
            }
            return result.ToArray();
        }
    }
相关标签: c#