LINQ选择所有项目,而不是从'where'
本文关键字:where 选择 项目 LINQ | 更新日期: 2023-09-27 18:05:53
我有一个Student对象列表,包含Id
, FirstName
和LastName
。
我有一份迟到学生的学号列表。我想用LINQ查询找到迟到的学生的名字。
但是,我的代码没有返回请求的名称。它返回每个数字的所有学生的名字我不知道我的linq查询出了什么问题
foreach (string studentnumber in pNumbers)
{
MessageBox.Show(studentnumber);
int snumber = Int32.Parse(studentnumber);
//var studentNames = from student in students where student.Id == snumber select new { FirstName = student.FirstName, LastName = student.LastName };
var studentNames = from student in students where student.Id == snumber select new { FirstName = student.FirstName, LastName = student.LastName };
foreach (var s in studentNames)
{
string name = s.FirstName + " " + s.LastName;
presentNamesList.Add(name);
}
下面是我如何做的一个例子
List<student> students = new List<student>();
students.Add(new student(1,"John","Doe"));
students.Add(new student(2,"Foo","Fighter"));
students.Add(new student(3,"Bob","Builder"));
students.Add(new student(4,"jack","ninja"));
List<int> nothere = new List<int>() { 2, 4 };
var present = students.Where(x => !nothere.Contains(x.studentid)).ToList();
列表present
现在应该包含不在nothere
列表中的学生
你可以这样做:
foreach (string studentnumber in pNumbers)
{
int snumber = Int32.Parse(studentnumber);
foreach(var s in students.Where(s=>s.Id == snumber))
{
presentNamesList.Add(s.FirstName + " " + s.LastName);
}
}
编辑:一个班轮:
presentNamesList.AddRange(students.Where(s=>!pNumbers.Contains(s.Id.ToString())).Select(s.Firstname + " " + s.Lastname).Select(s1=>s1.FirstName + " " + s1.LastName).ToList())