using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//泛型集合命名空间
using System.Collections.Generic;
//引入命名空间:using System.Collections.Generic;
//确定存储类型:List
////////////////////////////////////////常用的方法:
//添加元素:Add(
//删除元素:RemoveAt(索引);
////////////////////////////////////////常用属性:
//元素个数:Count
////////////////////////////////////////遍历集合
//foreach (Student stu in students)
//{
//Cosole.WriteLine(stu.StudentName);
//}
namespace _1.泛型集合List
{
class Program
{
static void Main(string[] args)
{
//创建几个学员对象
Student objStu1 = new Student(1001, "张三");
Student objStu2 = new Student(1002, "李四");
Student objStu3 = new Student(1003, "王五");
Student objStu4 = new Student(1004, "马六");
//创建集合对象
List<Student> stuList = new List<Student>();
stuList.Add(objStu1);
stuList.Add(objStu2);
stuList.Add(objStu3);
stuList.Add(objStu4);
stuList.Add(new Student()//使用对象初始化器
{
StudentId = 1005,
StudentName = "李雪"
});
//stuList.AddRange 加入集合数组的方法
//获取元素的个数
int numCount = stuList.Count();
//删除一个元素
stuList.Remove(objStu1);
stuList.RemoveAt(0);
//插入一个对象
stuList.Insert(0, new Student(10000, "德利"));
//遍历集合
foreach (Student item in stuList)
{
Console.WriteLine(item.StudentName + "\t" + item.StudentId);
}
Console.WriteLine("- - - - - - -");
//使用集合初始化器初始化泛型集合
List<Student> list = new List<Student>()
{
objStu1,
objStu2,
objStu3,
objStu4
};
List<string> nameList = new List<string>()
{
"小王",
"小张",
"小李",
"小刘"
};
for (int i = 0; i < nameList.Count(); i++)
{
Console.WriteLine(nameList[i]);
}
Console.ReadKey();
}
}
class Student
{
public Student()
{
}
public Student(int stuId, string stuName)
{
this.StudentId = stuId;
this.StudentName = stuName;
}
public int StudentId { get; set; }
public string StudentName { get; set; }
public int Age { get; set; }
}
}
原文:https://www.cnblogs.com/cq752522131/p/14208069.html