【问题标题】:simple select query in linqlinq中的简单选择查询
【发布时间】:2012-10-03 07:07:21
【问题描述】:

假设我有一个学生表,我想显示 ID 为 1 的学生。

SELECT *
FROM STUDENT ST
WHERE ST.ID = 1

这就是我在 Linq 中实现这一点的方式。

StudentQuery = from r in oStudentDataTable.AsEnumerable()
                                     where (r.Field<int>("ID") == 1)
                                     select r;
            oStudentDataTable = StudentQuery.CopyToDataTable();

但是如果我想显示这些 id 为 1,2,3,4,5..的学生怎么办?

SELECT *
FROM STUDENT ST
WHERE ST.ID IN (1,2,3,4,5)

如何在 Linq 中实现这一点?

【问题讨论】:

    标签: c# sql .net linq contains


    【解决方案1】:

    使用.Contains

    var list = new List<int> { 1, 2, 3, 4, 5 };
    
    var result = (from r in oStudentDataTable.AsEnumerable()
                  where (list.Contains(r.Field<int>("ID"))
                  select r).ToList();
    

    【讨论】:

    • 我自己更喜欢HashSet&lt;int&gt;,以防列表变得更长。
    • List 将由 LINQ-to-SQL 转换为 in 子句,然后由数据库优化。我不认为HashSet 会更快。
    • 您能否为此提供一些帮助:stackoverflow.com/questions/44764687/…
    【解决方案2】:

    试试IEnumerable.Contains:

    var list = new List<int>(){1,2,3,4,5};
    StudentQuery = from r in oStudentDataTable.AsEnumerable()
                                     where (list.Contains(r.Field<int>("ID")))
                                     select r;
            oStudentDataTable = StudentQuery.CopyToDataTable();
    

    【讨论】:

      【解决方案3】:

      也试试这个:

      var list = new List<int> { 1, 2, 3, 4, 5 };
      
      List<StudentQuery> result = (from r in oStudentDataTable.AsEnumerable()
                    where (list.Contains(r.Field<int>("ID"))
                    select new StudentQuery
                    { /*
                      .Your entity here
                      .
                      */
                    }).ToList<StudentQuery>();
      

      【讨论】:

        猜你喜欢
        • 2018-12-26
        • 1970-01-01
        • 2016-04-13
        • 2014-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多