【问题标题】:Pass int array in where clause of LINQ Query在 LINQ 查询的 where 子句中传递 int 数组
【发布时间】:2013-03-13 08:58:58
【问题描述】:

有一个类

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

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

【问题讨论】:

  • 每个学生都有唯一的 ID 吗?
  • 另外:id 列表会不会很长(比如超过学生列表大小的 5%)?只是想弄清楚是否值得在搜索之前创建一个按 ID 排序的学生列表。
  • 是的,它可能是大小的 5% 左右

标签: c# linq generics


【解决方案1】:

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

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

【讨论】:

  • 你能解释一下这在内部是如何工作的,比如如果列表很大,它会影响性能吗??
  • 看起来会是 O(N*M),其中 N = 学生人数,M = ID 人数。但我认为你不能做得更好。
  • @ankur,LINQ 内部使用迭代,因此它会根据 id 数组检查每个学生 id。这在与数据库交互时很有用,因为这将创建一个 Select * from table where ID in (1,2,3) 类型的查询。更多详情请访问wekeroad.com/2008/02/27/creating-in-queries-with-linq-to-sql
  • 不幸的是,在这种情况下它不会在数据库上执行,因为“studentList”是一个列表而不是一个 IQueryable。
  • @JustAnotherUserYouMayKnow,是的,这就是问题
【解决方案2】:

试试

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

【讨论】:

    【解决方案3】:

    我认为已经给出的答案已经足够快了,但是以防测试后你发现它太慢了:你可以在搜索之前尝试将学生列表转换为字典。

    你应该只在仔细的计时测试之后使用它,因为在大多数情况下它可能会慢很多!

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

    【讨论】:

      猜你喜欢
      • 2010-10-24
      • 1970-01-01
      • 1970-01-01
      • 2020-12-31
      • 2018-07-17
      • 1970-01-01
      • 1970-01-01
      • 2018-08-14
      相关资源
      最近更新 更多