文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>四种方法把string[]转换为int[]

四种方法把string[]转换为int[]

时间:2010-11-01  来源:天行健 自强不息

 

        static void Main(string[] args)
        {
            //测试字符串
            StringBuilder test;
            string[] str;
            for (int j = 0; j < 6; j++)
            {
                test = new StringBuilder();
                for (int i = 1; i <= (int)Math.Pow(10,j+1); i++)
                {
                    test.Append(i + ",");
                }
                test.Append("1");
                Console.WriteLine("元素个数为"+(int)Math.Pow(10, j + 1)+":");

                str = test.ToString().Split(',');
                StringToInt(str);
                StringToIntByLinq(str);
                StringToIntByArr(str);
                StringToIntByList(str);
                Console.WriteLine();
            }

            Console.Read();
        }

        //最简单的,用循环
        public static void StringToInt(string[] str)
        {
            long t1 = DateTime.Now.Ticks;
            int[] intArr = new int[str.Length];
            for (int i = 0; i < str.Length;i++ )
            {
                intArr[i] =Convert.ToInt32(str[i]);
            }
            Console.WriteLine("Loop Cost Time:" + (DateTime.Now.Ticks - t1));
        }

        //用Linq
        public static void StringToIntByLinq(string[] str)
        {
            long t1 = DateTime.Now.Ticks;
            int[] intArr = str.Select(o => Convert.ToInt32(o)).ToArray<int>();
            Console.WriteLine("Linq Cost Time:" + (DateTime.Now.Ticks - t1));
        }

        //用.NET中的数组转换方法
        public static void StringToIntByArr(string[] str)
        {
            long t1 = DateTime.Now.Ticks;
            int[] intArr = Array.ConvertAll<string, int>(str, Convert.ToInt32);
            Console.WriteLine("Arr  Cost Time:" + (DateTime.Now.Ticks - t1));
        }

        //用泛型
        public static void StringToIntByList(string[] str)
        {
            long t1 = DateTime.Now.Ticks;
            int[] intList = str.ToList<string>().ConvertAll<int>(Convert.ToInt32).ToArray<int>();
            Console.WriteLine("List Cost Time:" + (DateTime.Now.Ticks - t1));
        }

 

运行后效果为:

元素个数为10:
Loop Cost Time:0
Linq Cost Time:0
Arr  Cost Time:0
List Cost Time:0

元素个数为100:
Loop Cost Time:0
Linq Cost Time:0
Arr  Cost Time:0
List Cost Time:0

元素个数为1000:
Loop Cost Time:0
Linq Cost Time:0
Arr  Cost Time:0
List Cost Time:0

元素个数为10000:
Loop Cost Time:0
Linq Cost Time:156000
Arr  Cost Time:0
List Cost Time:0

元素个数为100000:
Loop Cost Time:468001
Linq Cost Time:468001
Arr  Cost Time:468001
List Cost Time:312000

元素个数为1000000:
Loop Cost Time:2496004
Linq Cost Time:2808005
Arr  Cost Time:2184004
List Cost Time:2340004

       大家如果有什么好的方法,也让我学习学习哦!
相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载