泛型集合 list

iamzxf發表於2015-05-08

    List<T>是ArrayList的泛型等效類,兼具有泛型的優點以及ArrayList的優點,使用它可以限制集合中儲存資料的型別,如果是不相容的型別會出現編譯錯誤,具有型別安全的特徵。語法格式有三種:
    (1)List<T> 列表名=new List<T>();
    (2)List<T>列表名=new List<T>(int capacity);
    (3)List<T>() others=new List<T>(IEnumerable<T>collection);

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

namespace listTDemo
{
    class Student
    {
        public string Name { set; get; }
        public string Sno { set; get; }
        public Student() { }
        public Student(string sno, string name)
        {
            this.Sno = sno;
            this.Name = name;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<Student> myset = new List<Student>();
            myset.Add(new Student("123", "zhangsan"));
            myset.Add(new Student("233", "lisi"));

            for (int i = 0; i < myset.Count; i++)
                Console.WriteLine("{0},{1}",myset[i].Sno, myset[i].Name);

            Console.WriteLine("===============");

            foreach(Student stu in myset)
                Console.WriteLine("{0},{1}", stu.Sno,stu.Name);

            Console.WriteLine("===============");

            List<Student> others = new List<Student>(myset);

            for (int i = 0; i < others.Count; i++)
                Console.WriteLine("{0},{1}", myset[i].Sno, myset[i].Name);

            Console.WriteLine("===============");

            foreach (Student stu in others)
                Console.WriteLine("{0},{1}", stu.Sno, stu.Name);

            Console.ReadLine();
        }
    }
}



相關文章