searching list of objects
I have a List of Student objects as such: List<StudentInfo>
. Now the StudentInfo object has certain parameters such as Name, ID and Attendance. I want to search the list by two things. I want to search by student Name and student id. The query should return the Attendance count for the studentInfo object. Here is what i have tried:
return studentInfoList
.Select((item) => new { value = item })
.Where(item => item.value.StudentName.Equals(name)
&&开发者_运维知识库 item.value.StudentID.Equals(id))
.Select(item => item.value.Attendance);
How can i do this?
Use Count()
method:
return studentInfoList
.Where(item => item.StudentName.Equals(name)
&& item.StudentID.Equals(id))
.Select(item => item.Attendance.Count());
// find student using conditions, suppose it may be only one
var student = studentInfoList
.SingleOrDefault(item => item.StudentName.Equals(name)
&& item.StudentID.Equals(id));
// found
if (student != null)
{
return student.Attendance;
}
else
{
// not found
}
I would try this
return studentInfoList.First(s => s.Name == name && s.StudentId == id).Attendance
Why is studentId not enough to locate a student?
Your data structure is hard to understand, but I've tried to simplify it and clean up.
return studentInfoList
.Single(si => si.StudentName == name || si.StudentID == id)
.Attendance;
I've assumed you only need the name or the id to find a student, not both. Also that Attendance is an integer, not an array. And that you need to make sure it is only for a single student, and if the student isn't found it should throw an exception.
// return the student with the given name and ID or null, if it cannot be found
StudentInfo student =
studentInfoList.Where(item => item.StudentName == name
&& item.StudentID == id).SingleOrDefault();
if (student == null) {
// student not found
} else {
return student.Attendance;
}
If you are talking the Attendance property of the item found, you just need:
var count = studentInfoList
.Where(item => item.StudentName.Equals(name) && item.StudentID.Equals(id))
.Select(item => item.Attendance).FirstOrDefault();
精彩评论