simple select query in linq

…衆ロ難τιáo~ 提交于 2019-12-23 06:58:56

问题


Lets say I have a student table and I want to display the student with ID 1.

SELECT *
FROM STUDENT ST
WHERE ST.ID = 1

This is how I achive this in Linq.

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

but what if I want to display the students with these ids 1,2,3,4,5..

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

How can I achieve this in Linq?


回答1:


Use .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();



回答2:


Try 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:


Try this also :

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


来源:https://stackoverflow.com/questions/12859536/simple-select-query-in-linq

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