首页 > 其他 > 详细

11.泛型集合List

时间:2020-12-29 20:12:50      阅读:29      评论:0      收藏:0      [点我收藏+]

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

//泛型集合命名空间
using System.Collections.Generic;

region 泛型集合List

//引入命名空间:using System.Collections.Generic;
//确定存储类型:List students=new List();
////////////////////////////////////////常用的方法:
//添加元素:Add();
//删除元素:RemoveAt(索引);
////////////////////////////////////////常用属性:
//元素个数:Count
////////////////////////////////////////遍历集合
//foreach (Student stu in students)
//{
//Cosole.WriteLine(stu.StudentName);
//}

endregion

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; }

}

}

11.泛型集合List

原文:https://www.cnblogs.com/cq752522131/p/14208069.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!