我有一个学生对象列表,其中包含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);
}
答案 0 :(得分:0)
以下是我将如何做到这一点的例子
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
列表中的学生
答案 1 :(得分:0)
您可以使用:
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())