Reputation: 1
I am unable to update the details after retrieving the list item by index(How should I update the details after retrieving a list item?)
try
{
Console.WriteLine("Updating the student details");
Console.WriteLine("Enter the index at which to update a student details");
int index = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < Student.Count; i++)
{
if(i==index)
{
Console.WriteLine("Id:{0} \nName:{1} \nMarks:{2}", Student[i].Name, Student[i].ID, Student[i].Marks);
}
Console.WriteLine("What details you want to update?");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
break;
Expected Output-->The code should except user input in Int form and fetch the details(by using the index) and return the fetched details to user, then user should be able to modify the details and the modified details should be updated to the list of student details.The Student list contains(string Name,int ID,int Marks).
Upvotes: 0
Views: 269
Reputation: 166
You can use a menu with a key to update individual property of the student.
Here is the student class:
public class Student
{
public Student(int id, string name, int marks)
{
ID = id;
Name = name;
Marks = marks;
}
public int ID { get; set; }
public string? Name { get; set; }
public int Marks { get; set; }
public override string ToString()
{
return $"Id: {ID} \nName:{Name} \nMarks:{Marks}";
}
}
I have overridden ToString() to format print the student detail.
Insertion of dummy data into studentList,
Random generator = new Random();
List<Student> studentList = new List<Student>();
for (int i = 1; i <= 5; i++)
{
studentList.Add(
new Student(i, $"Student {i}", generator.Next(60, 101))
);
}
Implementation of updating part with index out of bound check,
try
{
Console.WriteLine("Enter the index at which to update a student details");
int index = Convert.ToInt32(Console.ReadLine());
if (index >= studentList.Count)
throw new Exception("Out of bound student index");
Console.WriteLine(studentList[index]);
Console.WriteLine("What details you want to update?");
Console.WriteLine("1. ID\n2. Name\n3.Marks");
int choice = Convert.ToInt32(Console.ReadLine());
switch(choice)
{
case 1:
Console.WriteLine("Enter new ID: ");
int newId = Convert.ToInt32(Console.ReadLine());
studentList[index].ID = newId;
break;
case 2:
Console.WriteLine("Enter new Name: ");
string newName = Console.ReadLine() ?? "";
studentList[index].Name = newName;
break;
case 3:
Console.WriteLine("Enter new Marks: ");
int newMarks = Convert.ToInt32(Console.ReadLine());
studentList[index].Marks = newMarks;
break;
default:
Console.WriteLine("Invalid choice");
break;
}
Console.WriteLine(studentList[index]);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
Upvotes: 3