List的 Select()使用方法 Demo

List的 Select()使用方法

用List存储对象,代码如下:

IList<Student> studentList = new List<Student>();
for(int i=0;i<1000;i++)
{
   Student student = new Student();
    //赋值
    studentList.Add(student);
}

现在需要从studentList中查询符合条件的对象,Student中有个ClassName字段,需要从studentList中查询ClassName为“高一(3)班”的所有学生,一般是这样做的:

foreach(Student student in studentList)
{
  if(student.ClassName=="高一(3)班")
    {
      newList.Add(student);
      continue;
      }
}

但这种方法比较笨重,请看如下的方法。。

var newList = studentList.Where(s=>s.ClassName=="高一(3)班").ToList();

 

 另一种方法:

    List<Student> stu = studentList.FindAll(delegate(Student student)
    {
        if (student.Name.Equals("高一(3)班"))
        {
            return true;
        }
        else
        {
            return false;
        }
    });

 

posted on 2015-09-30 10:46  狼来了  阅读(2810)  评论(0编辑  收藏  举报