您的位置:首页 > 其它

对泛型集合进行筛选

2012-02-28 15:30 232 查看
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.条件});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: