web-dev-qa-db-fra.com

requête de sélection simple dans linq

Disons que j'ai une table d'étudiant et que je veux afficher l'étudiant avec l'ID 1.

SELECT *
FROM STUDENT ST
WHERE ST.ID = 1

C'est ainsi que j'y parviens à Linq.

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

mais si je veux afficher les étudiants avec ces identifiants 1,2,3,4,5 ..

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

Comment puis-je y parvenir dans Linq?

12
Bonus Kun

Utilisation .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();
20
Darren

Essayez 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();
4
Piotr Zierhoffer

Essayez aussi ceci:

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>();
2
Arun Manjhi