C#编程-100:List泛型学习_彭世瑜_新浪博客

91 阅读1分钟

集合与数组比较:

(1)长度可以改变

(2)添加数据时,不必考虑具体类型

  1. using System;

  2. using System.Collections;

  3. using System.Collections.Generic;

  4. using System.Linq;

  5. using System.Text;

  6.  

  7. namespace GenericTest

  8. {

  9.     class Program

  10.     {

  11.         static void Main(string[] args)

  12.         {

  13.             List<</span>int> list = new List<</span>int>();

  14.             list.Add(1);

  15.             list.Add(2);

  16.             list.Add(3);

  17.             list.AddRange(new int[]{4,5,6,7,8});

  18.             list.AddRange(list);//将自身作为参数添加到列表

  19.  

  20.             Console.WriteLine("======输出=======");

  21.             for(int i=0;i

  22.                 Console.WriteLine(list[i]);

  23.              

  24.             Console.WriteLine("======反转=======");

  25.             list.Reverse();

  26.             for (int i = 0; i < list.Count; i++)

  27.                 Console.WriteLine(list[i]);

  28.              

  29.             Console.WriteLine("======排序大到小=======");

  30.             list.Sort();

  31.             for (int i = 0; i < list.Count; i++)

  32.                 Console.WriteLine(list[i]);

  33.              

  34.             Console.WriteLine("======插入=======");

  35.             list.Insert(3,100);

  36.             for (int i = 0; i < list.Count; i++)

  37.                 Console.WriteLine(list[i]);

  38.  

  39.             Console.WriteLine("======删除=======");

  40.             list.Remove(3);

  41.             for (int i = 0; i < list.Count; i++)

  42.                 Console.WriteLine(list[i]);

  43.  

  44.             Console.WriteLine("======数组与列表互转=======");

  45.             int[] nums = list.ToArray();

  46.             List<</span>int> list2 = nums.ToList();

  47.             Console.ReadKey();

  48.         }

  49.     }

  50. }