Get the value from Model into List object

Polachan Paily 91 Reputation points
2022-05-24T22:11:18.667+00:00

I have a student class with the following attributes and values. I am storing the first record of a student in a class into student object variable and how could I get the value of the first student in to List. How can I get the value of first student from the class into firstStudent variable

List<Student> studentList = new List<Student>() { 
            new Student() { StudentID = 1, StudentName = "John"} ,
            new Student() { StudentID = 2, StudentName = "Moin"} ,
            new Student() { StudentID = 3, StudentName = "Bill"} ,
            new Student() { StudentID = 4, StudentName = "Ram"} ,
            new Student() { StudentID = 5, StudentName = "Ron"} 
        };

Student student = new Student();

 foreach (var students in class.students)
   {

       student = students;
       break;

   }

List<Student> firstStudent = new List<Student>();  

fistStudent should be stored with value of a first student from the class

Developer technologies | ASP.NET | ASP.NET Core
{count} votes

Answer accepted by question author
  1. Anonymous
    2022-05-25T01:34:38.297+00:00

    Hi @Polachan Paily ,

    You can try to use the Enumerable.First() Method or LINQ Query to filter the data and get the first student.

    Code like this:

             List<Student> studentList = new List<Student>() {  
                 new Student() { StudentID = 1, StudentName = "John"} ,  
                 new Student() { StudentID = 2, StudentName = "Moin"} ,  
                 new Student() { StudentID = 3, StudentName = "Bill"} ,  
                 new Student() { StudentID = 4, StudentName = "Ram"} ,  
                 new Student() { StudentID = 5, StudentName = "Ron"}  
             };  
            //use the first method.  
            Student firststudent = studentList.First();  
            //use the LINQ query   
            Student firststudent2 = studentList.Where(c => c.StudentID == 1).First();  
    
            //find the student by id.  
            List<Student> filterstudent = studentList.Where(c => c.StudentID == 1).ToList();   
    

    The result as below:

    205218-2.gif


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.