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
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"};
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 created 3 objects of a class and I want to display on the console how many objects I have created (using a static class variable) - How do I do this ?
I put public static int count = 0; in the class I created but I couldn't get it to increment (count++;) based on how many objects I created of the class. I created the 3 objects in the main method and gave them values for variables.
here is the class I created in my program :
public class Student
{
public static int count = 0;
// count++;
private string firstName;
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
private string lastName;
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
private string birthDate;
public string BirthDate
{
get { return birthDate; }
set { birthDate = value; }
}
}
In the main method I created 3 objects of class Student:
static void Main(string[] args)
{
// Create 3 students
Student student1 = new Student
{
FirstName = "John",
LastName = "Wayne",
BirthDate = "26/05/1907"
};
Student student2 = new Student
{
FirstName = "Craig",
LastName = "Playstead",
BirthDate ="01/01/1967"
};
Student student3 = new Student
{
FirstName = "Paula",
LastName = "Smith",
BirthDate = "01/12/1977"
};
// Console.WriteLine("The course contains {1} students(s) " studentCounter );
I can't get the counter to ++ based on the way I created the objects.
Increment the count in the constructor:
public class Student
{
public static int count = 0;
public Student()
{
// Thread safe since this is a static property
Interlocked.Increment(ref count);
}
// use properties!
public string FirstName { get; set; }
public string LastName { get; set; }
public string BirthDate { get; set; }
}
You just need a constructor, there you can increment the count.
public Student()
{
count++;
}
You can increment the counter in the constructor
public Student()
{
count++;
}
To print the count variable
we should write some code like below
public static int GetCount()
{
return count;
}
and main class look like :
static void Main(string[] args)
{
// Create 3 students
Student student1 = new Student
{
FirstName = "John",
LastName = "Wayne",
BirthDate = "26/05/1907"
};
Student student2 = new Student
{
FirstName = "Craig",
LastName = "Playstead",
BirthDate ="01/01/1967"
};
Student student3 = new Student
{
FirstName = "Paula",
LastName = "Smith",
BirthDate = "01/12/1977"
};
//To print the count
Console.WriteLine(" Number of Objects is : "+Student.GetCount());
}
and if we have parameterized constructor then we also have to write count++ in that constructor.
I have a dataset which returns a couple of contact information in string(Phone, mobile, skype). I created an object with a Dictionary property where i can put the contact information in a key value pair. The problem is, I am assigning the values of the object using Linq. Hope somebody can help. Here is my code:
public class Student
{
public Student()
{
MotherContacts = new ContactDetail();
FatherContacts = new ContactDetail();
}
public ContactDetail MotherContacts { get; set; }
public ContactDetail FatherContacts { get; set; }
}
public class ContactDetail
{
public ContactDetail()
{
Items = new Dictionary<ContactDetailType, string>();
}
public IDictionary<ContactDetailType, string> Items { get; set; }
public void Add(ContactDetailType type, string value)
{
if(!string.IsNullOrEmpty(value))
{
Items.Add(type, value);
}
}
}
public enum ContactDetailType
{
PHONE,
MOBILE
}
Here's how I assign value to the Student object:
var result = ds.Tables[0].AsEnumerable();
var insuranceCard = result.Select(row => new Student()
{
MotherContacts.Items.Add(ContactDetailType.PHONE, row.Field<string>("MotherPhone"),
MotherContacts.Items.Add(ContactDetailType.MOBILE, row.Field<string>("MotherMobile")
}).FirstOrDefault();
The compiler says that the MotherContacts is not recognized in the context. What should I do?
I think your code should look like:
var insuranceCard = result.Select(row =>
{
var s = new Student();
s.MotherContacts.Items.Add(ContactDetailType.PHONE, row.Field<string>("MotherPhone");
s.MotherContacts.Items.Add(ContactDetailType.MOBILE, row.Field<string>("MotherMobile");
return s;
}).FirstOrDefault();
You are using the object initializer syntax in a wrong way. The correct use is:
new Student{MotherContacts = value} where value must be a ContactDetail.
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.