In my program I have a list of marks and a dictionary which stores the studentId. I want that the user enters the studentId and according to that id it will point to the list of marks. I think I am implementing it incorrectly. Can someone help me in implementing it. Thanks
public class Student() {
private string name;
private string surname;
private string dob;
private string address;
private int id;
public Student()
{
}
public Student(string year,string name, string surname, string dob, string address)
{
this.name = name;
this.surname = surname;
this.dob = dob;
this.address = address;
this.year = year;
}
public string Name
{
get { return name; }
set { name = value; }
}
public string Surname
{
get { return surname; }
set { surname = value; }
}
public string DOB
{
get { return dob; }
set { dob = value; }
}
public string Addr
{
get { return address; }
set { address = value; }
}
public int Id
{
get { return id; }
set { id = value; }
}
private string year;
public string Year
{
get { return year; }
set { year = value; }
}
public Student(string s)
{
string[] splitted = s.Split(',');
name = splitted[0];
surname = splitted[1];
dob = splitted[2];
address = splitted[3];
// id = splitted[4];
}
public Dictionary<int,List<Marks>> dictionary= new Dictionary<int,List<Marks>>();
public List<Marks> Mathematics = new List<Marks>();
public List<Marks> English = new List<Marks>();
public List<Marks> Maltese = new List<Marks>();
public List<Marks> ReligiousStudies = new List<Marks>();
public List<Marks> SocialStudies = new List<Marks>();
public Dictionary<int, List<Marks>> dictionar = new Dictionary<int, List<Marks>>();
public void AddMarks(int hyexam, int anexam)
{
{
Console.WriteLine("enter id of student to input marks to:");
string id = Console.ReadLine();
if (dictionar.ContainsKey(Id).Equals(id))
{
Mathematics.Add(new Marks(hyexam, anexam));
English.Add(new Marks(hyexam, anexam));
Maltese.Add(new Marks(hyexam, anexam));
ReligiousStudies.Add(new Marks(hyexam, anexam));
SocialStudies.Add(new Marks(hyexam, anexam));
dictionar.Add(id, (Mathematics)); //dont know how to implement it
}
else
{
Console.WriteLine("id not found");
}
}
}
public class Marks
{
private int hyexam;
private int anexam;
private string id;
public int HYEXAM
{
get { return hyexam; }
set { hyexam = value; }
}
public int ANEXAM
{
get { return anexam; }
set { anexam = value; }
}
public string Id
{
get { return id; }
set { id = value; }
}
public Marks(int hyexam, int anexam)
{
this.hyexam = hyexam;
this.anexam = anexam;
}
public Marks(string id)
{
this.id = id;
}
public double OverallExam()
{
return (0.4 * hyexam) + (0.6 * anexam);
}
}
}
I'd say the main problem is your modelling. You've included the Dictionary<int, List<Marks>> as a field within Student. That means that each Student object has a dictionary. That makes no sense - because the key for the dictionary is meant to be the student ID, right?
It probably makes sense for each Student object to the lists of marks as you've currently got (although not as public fields, IMO). Given that information, do you really need a Dictionary going to the marks at all? Wouldn't it be cleaner to have a Dictionary<int, Student> somewhere (not in the Student class - maybe in a School class?) mapping each student ID to a Student, and you can get the marks from the Student?
Think hard about what you're trying to achieve, and where the data really belongs. In my experience, when you've got the data modelling right, the code usually follows in a clean way.
(I'd also question your Marks class, both in terms of name and design. What are those properties meant to represent? Isn't it really a single mark in an exam? Perhaps ExamResult would be clearer? Does it really need to be mutable?)
I'd agree with Jon that this is definitely a modeling issue (based on the OP's other posts). If you're new to object oriented programming, the first thing you need to do is determine what objects you'll need to create to answer the problem.
What is a Student? A student has a name, id, dob, class year, etc. For every attribute a student has, you need to set up a field or property.
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime DoB { get; set; }
... etc ...
}
What is a Mark? From your descriptions, a Mark has a subject, a mid-exam score, and an annual-exam score.
public class Mark
{
public string Subject { get; set; }
public int MidScore { get; set; }
public int FinalScore { get; set; }
}
What is the relationship between a Student and a Mark? A student has a list of marks associated with them. This is best described with a List<> object.
public class Student() // continued
{
public List<Mark> Marks { get; set; }
}
Once you have the basics set up for your objects, it will be easier to filter out what you DON'T need, and make it much easier to answer your question. :)
My proposal:
Your "Mark" class must have something that identifies the subject (could be an enum called Subject, or an string, or an int with the ID of the subject if you have it stored in database)
Then you could have:
Console.WriteLine("enter id of student to input marks to:");
string id = Console.ReadLine();
var marks = new Dictionary<int, List<Mark>>();
if (UserExists(id))
{
Console.WriteLine("mark for subject1:");
string s1 = Console.ReadLine();
Console.WriteLine("mark for subject2:");
string s2 = Console.ReadLine();
var list = new List<Mark>();
list.Add(new Mark { Subject = SubjectEnum.Subject1, Value = Convert.ToDecimal(s1), });
list.Add(new Mark { Subject = SubjectEnum.Subject2, Value = Convert.ToDecimal(s2), });
marks.Add(Convert.ToInt32(id), list)
}
else
{
Console.WriteLine("id not found");
}
Hope this helps.
Related
I can update a List using "single line" updates, but I'd like to update multiple items on a single line, similar to the way the List is initialized.
Here is my code:
public class Players
{
public int id;
public string Rank = "";
public string PlayerName = "";
public string LName = "";
public string FName = "";
public string Team = "";
}
List<Players> newList = new List<Players>();
newList.Add(new Players() { id = 111, PlayerName = "Alpha" });
newList.Add(new Players() { id = 222, PlayerName = "Beta" });
newList.Add(new Players() { id = 333, PlayerName = "Gamma" });
newList[0].FName = "Joe";
newList[0].LName = "Smith";
newList[0].Team = "Yankees";
// newList[1] ={ FName="Babe" , Lname="Ruth", Team="Boston"};
foreach(var item in newList)
{
Console.WriteLine(item.id+" "+item.PlayerName+" "+item.FName+" "+item.LName+" "+item.Team);
}
I want to use something like below to update the list object with multiple items with one line. But this line throws and exception "FName does not exist in current context"
This is the error line // newList[1] ={ FName="Babe" , Lname="Ruth", Team="Boston"};
How do I create/format the correct way to update a List object?
If you want to set those three properties with a one liner, why not implementing a method in the Player class?
public class Player {
//...
public void SetProperties(string Fname, string Lname, string team)
{
FName = fName,
LName = lName,
Team = team
}
}
Then you can do
var newList = new List<Player>();
//...
newList[0].SetProperties("Babe", "Ruth", "Boston");
Edit: #godot suggested that is better to have a method to update just some properties of the Player object. A way to achieve this goal is reflection and anonymous types.
I propose a refactoring of the SetProperties method:
public class Player
{
public int Id { get; set; }
public string Rank { get; set; }
public string PlayerName { get; set; }
public string LName { get; set; }
public string FName { get; set; }
public string Team { get; set; }
public void SetProperties(object obj)
{
foreach (var prop in obj.GetType().GetProperties())
{
var propertyToUpdate = this.GetType().GetProperty(prop.Name);
if(propertyToUpdate != null) propertyToUpdate.SetValue(this, prop.GetValue(obj));
}
}
By implementing this method you can update your list object like this:
newList[0].SetProperties( new { FName = "Babe", LName = "Ruth", Team = "Boston" } );
You can create/format the entire player by creating a new player and overwriting everything.
newList[1] = new Players() { FName="Babe" , Lname="Ruth", Team="Boston"};
Im trying to store these instances of student inside of this array.
Student:
public Student(string Value)
{
FirstName = Value;
LastName = Value;
StudentID = Value;
}
Here is the Array
string[] student = new string[4];
{ ElementarySchoolStudent, MiddleSchoolStudent, HighSchoolStudent, CollegeStudent }
Each constructor is like this and they use the Student method.
CollegeStudent(string value) : base(value) { }
How exactly would I go about storing these instances in the array? When I do it like that i get the error message:
college student is a type which is not valid in the given context.
What's the correct way to code it exactly?
From this and the last question, maybe you want something like this
Given
public class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string StudentID { get; set; }
}
Usage
var students = new Student[]
{
new Student(){FirstName = "bob",LastName = "blerg",StudentID = "23432"},
new Student(){FirstName = "dan",LastName = "flib",StudentID = "4564"},
new Student(){FirstName = "jib",LastName = "jab",StudentID = "564"},
};
foreach (var student in students)
Console.WriteLine($"{student.StudentID} : {student.FirstName}, {student.LastName}");
Output
23432 : bob, blerg
4564 : dan, flib
564 : jib, jab
Note : Add constructor or pepper and salt to taste
I have a list of Students in cache, and I wants to update an item, how can i do that.
public class Student
{
int id;
string name;
string address;
}
public void updateStudent(Student st)
{
var student = _cache.Get(CacheVariable.cache_data_student) as List<Student>;
//How to update student.
}
Maybe you can do it with a small query.
First Find this updated student is who?
And Find this student's place from List
Then Change This Place with new Value
var student = _cache.Get(CacheVariable.cache_data_student) as List<Student>;
Student findStudent = student.FirstOrDefault(x=> x.Id == st.Id);
int id = student.IndexOf(y);
student[id] = st;
or if you want you can use another thing for last row like :
student[id] = new Student()
{
id = x,
name = "y",
address = "z"
};
Probably there is a better solution for this situation but I don't know. I think this could be helpfull
Since the ID should be the unique identifier, use LINQ to get the student to update:
public void updateStudent(Student st)
{
Student studentToUpdate = _cache.FirstOrDefault(s => s.id == st.id)
studentToUpdate?.Update(st);
}
To update your student you need to implement your own method. Just set the properties like
public class Student
{
public int id { get; }
public string name { get; set; }
public string address { get; set; }
public void Update(Student st)
{
this.name = st.name;
this.address = st.address;
}
}
public class Student
{
int id;
string name;
string address;
}
public void updateStudent(Student st)
{
var student = _cache.Get(CacheVariable.cache_data_student) as List<Student>;
//First look for the st in Student list, you need the id field or primary key
var s = student.Where(x => x.idField == st.idField).FirstOrDefault();
s = st;
//student = st;//student.Update(st); //Not working. Only pass the value
}
I have a List that cointains some objects that have 2 string and 2 int properties. I would like to be able to display all the 4 properties of an object based on the content of its first property.
For example: I want to display all the data of all the items of the list that's first property is "Mozart".
Thanks in advance!
I have a really basic class that has 4 properties, 2 strings, and 2 ints, all of them have their respective getters/ setters set to public.
I also have a List that contains some of these objects.
My code looks like this.
Console.WriteLine("Give in the name you want to search for!");
string s = Console.ReadLine();
After this, I would like to check if the first property is "s", and if it is, display all of that given object's data on the screen.
Have a look at this and let me know if you're stuck with any of it :)
void Main()
{
List<Music> myMusic = new List<Music>
{
new Music
{
Artist = "Mozart",
Album = "Mozarts amazing album",
TotalTracks = int.MaxValue,
Etc = int.MinValue
},
new Music
{
Artist = "Foo",
Album = "Bar",
TotalTracks = int.MaxValue,
Etc = int.MinValue
},
};
var mozartsMusic = myMusic.Where(music => music.Artist == "Mozart")
.ToList();
mozartsMusic.ForEach(Console.WriteLine);
}
public class Music
{
public string Artist { get; set; }
public string Album { get; set; }
public int TotalTracks { get; set; }
public int Etc { get; set; }
public override string ToString()
{
return string.Join("\n",this.GetType().GetProperties().Select(p=>string.Format("{0} {1}", p.Name, p.GetValue(this))));
}
}
Something like this would do the trick:
class Datum
{
public string Composer { get; set; }
///wharever other proerties you need
public string DisplayOutput()
{
return this.Composer //+ however you want it displayed
}
}
class Program
{
static void Main(string[] args)
{
List<Datum> data = new List<Datum>();
foreach (var outputLine in data.Where(d => d.Composer == "Mozart").Select(d=>d.DisplayOutput())
{
Console.WriteLine(outputLine);
}
}
}
That should be a possible way to do so:
class Composer
{
public Composer( string lastName, string firstName, int year, int month )
{
LastName = lastName;
FirstName = firstName;
YearOfBirth = year;
MonthOfBirth = month;
}
public string LastName { get; set; }
public string FirstName { get; set; }
public int YearOfBirth { get; set; }
public int MonthOfBirth { get; set; }
public override string ToString()
{
return string.Format( "{0} {1} {2} {3}", LastName, FirstName, YearOfBirth.ToString(), MonthOfBirth.ToString() );
}
}
class Program
{
private static new List<Composer> composerList = new List<Composer>();
static void Main( string[] args )
{
composerList.Add( new Composer( "Mozart", "Wolfgang", 1756, 1 ) );
composerList.Add( new Composer( "Vivaldi", "Antonio", 1678, 3 ) );
Console.WriteLine( "Please enter a name you want to search for!" );
string name = Console.ReadLine();
ShowComposerData( name );
}
private static void ShowComposerData( string name )
{
foreach( Composer comp in composerList )
{
if( comp.LastName == name )
{
Console.WriteLine( comp.ToString() );
}
}
}
}
Say I have a class like this:
class public Person
{
public string firstName;
public string lastName;
public string address;
public string city;
public string state;
public string zip;
public Person(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
}
And let's further say I create a List of type Person like this:
List<Person> pList = new List<Person>;
pList.Add(new Person("Joe", "Smith");
Now, I want to set the address, city, state, and zip for Joe Smith, but I have already added the object to the list. So, how do I set these member variables, after the object has been added to the list?
Thank you.
You get the item back out of the list and then set it:
pList[0].address = "123 Main St.";
You can keep a reference to your object around. Try adding like this:
List<Person> pList = new List<Person>;
Person p = new Person("Joe", "Smith");
pList.Add(p);
p.address = "Test";
Alternatively you can access it directly through the list.
pList[0].address = "Test";
You can get the first item of the list like so:
Person p = pList[0]; or Person p = pList.First();
Then you can modify it as you wish:
p.firstName = "Jesse";
Also, I would recommend using automatic properties:
class public Person
{
public string firstName { get; set; }
public string lastName { get; set; }
public string address { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zip { get; set; }
public Person(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
}
You'll get the same result, but the day that you'll want to verify the input or change the way that you set items, it will be much simpler:
class public Person
{
private const int ZIP_CODE_LENGTH = 6;
public string firstName { get; set; }
public string lastName { get; set; }
public string address { get; set; }
public string city { get; set; }
public string state { get; set; }
private string zip_ = null;
public string zip
{
get { return zip_; }
set
{
if (value.Length != ZIP_CODE_LENGTH ) throw new Exception("Invalid zip code.");
zip_ = value;
}
}
public Person(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
}
Quite possibly not the best decision to just crash when you set a property here, but you get the general idea of being able to quickly change how an object is set, without having to call a SetZipCode(...); function everywhere. Here is all the magic of encapsulation an OOP.
You can access the item through it's index. If you want to find the last item added then you can use the length - 1 of your list:
List<Person> pList = new List<Person>;
// add a bunch of other items....
// ....
pList.Add(new Person("Joe", "Smith");
pList[pList.Length - 1].address = "....";
Should you have lost track of the element you're looking for in your list, you can always use LINQ to find the element again:
pList.First(person=>person.firstName == "John").lastName = "Doe";
Or if you need to relocate all "Doe"s at once, you can do:
foreach (Person person in pList.Where(p=>p.lastName == "Doe"))
{
person.address = "Niflheim";
}