对泛型集合进行筛选

来源:互联网 发布:潘多拉优化网络软转发 编辑:程序博客网 时间:2024/06/14 06:26
using System;using System.Collections.Generic;using System.Linq;using System.Text; namespace Test{    public class Student    {        public Student() { }        public Student(string name, int age)        {            this.name = name;            this.age = age;        }        private string name;        public string Name        {            get { return name; }            set { name = value; }        }        private int age;         public int Age        {            get { return age; }            set { age = value; }        }    }}  using System;using System.Collections.Generic;using System.Linq;using System.Text; namespace Test{    class Program    {        private static List<Student> list1 = new List<Student>();      //声明一个用于放置初始值的集合  注:必须声明List类型而不是IList接口类型        private static List<Student> list2 = new List<Student>();      //用户存放筛选结果        static void Main(string[] args)        {            //声明实例化student对象            Student stu1 = new Student("aa", 10);            Student stu2 = new Student("bb", 13);            Student stu3 = new Student("cc", 15);            Student stu4 = new Student("dd", 18);            //向集合中添加对象            list1.Add(stu1);                         list1.Add(stu2);            list1.Add(stu3);            list1.Add(stu4);                    Console.WriteLine(list1.Find(delegate(Student stu) { return stu.Age > 12; }).Name);            //返回筛选满足条件的第一个对象            list2 = list1.FindAll(delegate(Student stu) { return stu.Age > 12; });          //对泛型集合进行筛选            //遍历结果            foreach (Student stu in list2)            {                Console.WriteLine(stu.Name);            }        }    }}


泛型集合筛选的语法:

List<T> a=new List<T>();

List<T> b=new List<T>();

B=a.FindAll(delegate(T 对象t){return t.条件});


原创粉丝点击