参考书目:C#6.0学习笔记——从第一行C#代码到第一个项目设计(作者周家安)P220
内容:学习List<>的使用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Example7_9
{
class Program
{
static void Main(string[] args)
{
//实例化list
List<byte> byteList = new List<byte>();
//向列表中添加元素
byteList.Add(25);
byteList.Add(37);
//一次性添加多个元素
byteList.AddRange(new byte[] { 2, 16, 150 });
//通过索引输出
int listCount = byteList.Count;
Console.WriteLine("元素总数:{0}", listCount);
for(int i =0; i<listCount; i++)
{
Console.Write(" " + byteList[i]);
}
Console.Write("\n");
//--------------添加元素------------
byteList.Insert(2, 82); //在索引为2的位置插入一个元素,插在它前面
listCount = byteList.Count;
Console.WriteLine("插入82后的元素总数:{0}", listCount);
for (int i = 0; i < listCount; i++)
{
Console.Write(" " + byteList[i]);
}
Console.Write("\n");
//--------------删除加元素------------
Console.WriteLine("删除元素前的元素个数:{0}", byteList.Count);
foreach(byte n in byteList)
Console.Write(" " + n);
Console.WriteLine();
byteList.RemoveAt(byteList.Count - 1); //第1次删除
Console.WriteLine("第一次删除元素后(删除末尾元素),剩余的元素个数:{0}", byteList.Count);
foreach (byte n in byteList)
Console.Write(" " + n);
Console.WriteLine();
byteList.RemoveAt(2); //第2次删除,删除索引2处的元素
Console.WriteLine("第二次删除元素后(删除索引2处的元素),剩余的元素个数:{0}", byteList.Count);
foreach (byte n in byteList)
Console.Write(" " + n);
Console.WriteLine();
//------------进行排序---------
byteList.Add(2);
byteList.Add(45);
Console.WriteLine("排序前输出");
foreach (byte n in byteList)
Console.Write(" " + n);
Console.WriteLine();
byteList.Sort();
Console.WriteLine("排序后输出(由小到大,升序)");
foreach (byte n in byteList)
Console.Write(" " + n);
Console.WriteLine();
byteList.Reverse(); //先升序,再倒置就是降序
Console.WriteLine("排序后输出(由大到小,降序)");
foreach (byte n in byteList)
Console.Write(" " + n);
Console.WriteLine();
Console.ReadKey();
//
}
}
}
运行结果: