动态向数组中添加数据之Array,ArrayList,List,Dictionary用法

-------    Windows Phone 7手机开发 .Net培训、期待与您交流!  -------

Array:数组初始化的时候必须给定长度,因此数组是不能动态添加数据的。 System.Array.Resize这个泛型方法可以重置数组大小,  但该方法是创建新设置大小的数组,用的是旧数组的元素初始化。
        static void Array()
        {
            Console.Write("请输入数字,用“|”分给开:");
            string str = Console.ReadLine();
            string[] strArr= str.Split('|');//使用Split()方法将原字符串分割
            int[] arr=new int[strArr.Length];//创建一个字符串数组长度的整数数组
            for(int i=0;i<strArr.Length;i++)
            {
                Console.WriteLine(Convert.ToInt32(strArr[i]));
            }
            Console.ReadKey();
        }


ArrayList:对象被设计成为一个动态数组类型,其容量会随着需要而适当的扩充
        static void ArrayList()
        {
            ArrayList arrList = new ArrayList();
            for (int i = 0; i < 5; i++)
            {
                Console.Write("请输入数字:");
                int num =Convert.ToInt32 (Console.ReadLine());
                arrList.Add(num);
            }
            foreach(int i in arrList )
            {
                Console.Write(i);
            }
            Console.ReadKey();
        }


List:在决定使用  List 还是使用  ArrayList 类(两者具有类似的功能)时,记住  List 类在大多数情况下执行得更好并且是类型安全的。如果对  List 类的类型  T 使用引用类型,则两个类的行为是完全相同的。但是,如果对类型  T 使用值类型,则需要考虑实现和装箱问题。
        static void List()
        {
            List<int> list = new List<int>();
            for (int i = 0; i < 5; i++)
            {
                Console.Write("请输入数字:");
                int num = Convert.ToInt32(Console.ReadLine());
                list.Add(num);
            }
            foreach (int i in list)
            {
                Console.Write(i);
            }
            Console.ReadKey();
        }


Dictionary:表示键和值的集合。 Dictionary遍历输出的顺序,就是加入的顺序
<pre name="code" class="csharp">        static void Dictionary()
        {
            Dictionary<int, int> dict = new Dictionary<int, int>();//实例化一个键值集合
            for (int j = 0; j < 5; j++)
            {
                Console.Write("请输入数字:");
                int num = Convert.ToInt32(Console.ReadLine());
                dict.Add(j, num);//向键值集合中添加键、值
            }
            foreach (KeyValuePair<int, int> item in dict)
            {
                Console.Write(item.Value);
            }
            Console.ReadKey();
        }


 
 
 
 
 
 
 
 
 
 
 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值