6

有一堂课

Public class Student
{
  int id;
  int rollNum;
  String Name;
}

一个方法

Public List<Student> GetAllStudents()
{
  var studentList = GetMeAll(); // Simple select * query to get all students
  //unfortunately i can't make changes in this method so have to write a linq query to       //filter data.
  //getting int array ids correctly from some method
   var filterList = FilterStudentsByID(ids,StudentList);
}

我想编写一个将 int 数组作为输入并返回 List 的方法

Public List<Student> FilterStudentsByID(int[] ids,List<student> studentList)
{
  //There should be a linq query , but I am new to linq so don't know how to write this.
  Var list = from  studentList in ..... don't know much;
}

编写查询的任何帮助。谢谢大家的回答,我也在寻找保持大量记录的表演??如果您可以添加我对查询的简单解释将在内部工作,那就太好了?

4

3 回答 3

10

如果您要从列表中查找其 id 存在于ids数组中的学生,则:

var list = from s in stundentList
           where ids.Contains(s.ID)
           select s;
于 2013-03-13T09:00:30.280 回答
5

尝试

Var list = studentList.Where(s=>ids.Contains(s.id)).ToList();
于 2013-03-13T09:01:57.683 回答
1

I think the answers already given will be fast enough, but just in case after testing you find that it's too slow: You can try converting the student list to a dictionary before doing the searching.

You should only use this after careful timing tests, since it is likely to be a lot slower for most cases!

public static List<Student> FilteredStudents(int[] targetIds)
{
    var allStudents = GetAllStudents().ToDictionary(student => student.id);
    var result = new List<Student>();

    foreach (int id in targetIds)
    {
        Student student;

        if (allStudents.TryGetValue(id, out student))
        {
            result.Add(student);
        }
    }

    return result;
}
于 2013-03-13T09:27:07.693 回答