Pass int array in where clause of LINQ Query

痴心易碎 提交于 2020-02-03 05:15:10

问题


There is a class

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

a method

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);
}

I want to write a method that takes an int array as input and returns a 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;
}

Any help in writing the query. Thank you all for Answers, I am also looking for maintain the performances with large list of records ?? It will be great if you can add me simple explanation of the query will work internally ??


回答1:


If you are looking to find those students from the list whose id's are present in the ids array then:

var list = from s in stundentList
           where ids.Contains(s.ID)
           select s;



回答2:


try

Var list = studentList.Where(s=>ids.Contains(s.id)).ToList();



回答3:


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;
}


来源:https://stackoverflow.com/questions/15380774/pass-int-array-in-where-clause-of-linq-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!