现在的位置: 首页 > 综合 > 正文

黑马程序员_002集合类List

2016年05月21日 ⁄ 综合 ⁄ 共 1635字 ⁄ 字号 评论关闭
---------------------- ASP.Net+Unity开发.Net培训、期待与您交流! ----------------------

集合类List

一、知识点概述

  • 有时候不能预先确定长度或者需要动态修改内容和长度,这时候可以使用List<T>泛型集合,把T改成相应类型即可
  • List<T>,可以看做是动态的数组。Add、Clear、Count、Remove、RemoveAt、ToArray(转换为数组)
  • List<T>可以使用foreach遍历

二、源代码实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace jishuboke2
{
    class Program
    {
        //集合类List
        static void Main(string[] args)
        {
            //回顾数组的定义,赋值,输出
            int[] nums = new int[3];
            nums[0] = 1;
            nums[1] = 3;
            nums[2] = -67;
            Console.WriteLine("数组的输出:\n" );
            foreach (int i in nums)
            {
                Console.WriteLine(i.ToString() + "\n");


            }
            //数组缺点:长度固定,定义后数组下标不能越界
            // nums[3] = 4;
            Console.ReadLine();
            //集合能解决数组长度不确定的情况,下面是集合的使用:


            //定义一个整型集合
            List<int> l1 = new List<int>();
            //可增加多个集合元素
            l1.Add(1);
            l1.Add(3);
            l1.Add(-67);
            l1.Add(0);
            Console.WriteLine("整型集合的输出:\n" );
            foreach (int i in l1)
            {
                Console.WriteLine(i.ToString() + "\n");


            }
            Console.ReadLine();




            //定义一个字符串数组
            string[] str1 = new string[33];
            //定义一个字符串的集合
            List<string> str2=new List<string>() ;
            //给这个字符串集合赋值
            str2.Add("abc");
            str2.Add("ef");
            str2.Add("cde");
            //输出这个集合的元素数量
            Console.WriteLine("\n集合str2的元素数量:"+str2.Count.ToString());
            //删除集合中的某个元素
            str2.Remove("cde");
            Console.WriteLine("\n删除集合str2的元素后显示集合中的元素数量:"+str2.Count.ToString());
            //清除集合的元素
            str2.Clear();
             Console.WriteLine("\n清除集合str2的元素后再次显示集合中的元素数量:"+str2.Count.ToString());


             Console.ReadLine();


        }
    }
}

---------------------- ASP.Net+Unity开发.Net培训、期待与您交流! ----------------------详细请查看:www.itheima.com

抱歉!评论已关闭.