I am learning a MOOC course on c#. we had to create an Arraylist of type students and then using the foreach loop had to iterate over it and print the names. i have tried all casting methods but could not get through it. please help
c.students.Add(student1);
c.students.Add(student2);
c.students.Add(student3);
foreach(object o in students)
{
Student s = (Student)o;
Console.WriteLine(s.FirstName);
}
c is the course object. course is a class. students is the arraylist. Student is a class.
Not sure where you face the error. Check out my .NET Fiddle here. Code shown below as well. Hope it helps.
using System;
using System.Collections;
public class Program
{
public static void Main()
{
var students = new ArrayList();
students.Add(new Student() { FirstName = "John", LastName = "Doe" });
students.Add(new Student() { FirstName = "Richard", LastName = "Roe" });
foreach(Student s in students)
{
Console.WriteLine(s.FirstName);
}
}
}
public class Student
{
public string FirstName {get;set;}
public string LastName {get;set;}
}
foreach(object o in c.students)
this should do it, its probably a silly mistake
namespace stackOverflow
{
class Program
{
static void Main(string[] args)
{
course c = new course();
student student1 = new student("a");
student student2 = new student("b");
student student3 = new student("c");
c.students.Add(student1);
c.students.Add(student2);
c.students.Add(student3);
foreach (object o in c.students)
{
student s = (student)o;
Console.WriteLine(s.name);
}
}
}
class course
{
public List<student> students = new List<student>();
}
class student
{
public string name { get; set; }
public student(string s)
{
name = s;
}
}
}
ArrayList students = new ArrayList();
This line should be: c.students = new ArrayList(); as mentioned by Channs previously.
As you have written it, it is trying to create a new variable in your main function called students, it never accesses the students array inside your course object.
Although your initialisation of internal object variables should be done within the object itself.
So inside your course object do something more like this:
class Course
{
public ArrayList students;
public Course()
{
students = new ArrayList();
}
}
This way, whenever you declare a new object of type Course ( ie: Course c = new Course() ) it will initialise the array automatically.
Another issue I noticed was in your Student constructor declaration, you are always trying to take a parameter of string fname.
public Student(string fname)
Then in your code you never pass that data ie:
Student student1 = new Student();
So either pass the firstname variable in when you are initialising or change your constructor in Student to allow it to accept nothing as well as a firstname as shown below:
class Student
{
private string firstName;
private string lastName;
public Student(string fname = null)
{
this.FirstName = fname;
}
this way you don't have to pass the data, but if you do it will be copied over to the firstname of the student object.
You could always change the null to something like "John" or "No Name" so that you have printable data in the object. just a suggestion though.
Regards,
Slipoch
Here is your code fixed up. There were 2 things:
Your student class did not have a default constructor.
Your student array list was not initialized in the course class.
Hope this helps.
using System;
using System.Collections;
class Program
{
public static void Main(string[] args)
{
Student student1 = new Student();
student1.FirstName = "a";
student1.LastName = "w";
Student student2 = new Student();
student2.FirstName = "e";
student2.LastName = "s";
Student student3 = new Student();
student3.FirstName = "i";
student3.LastName = "o";
Course c = new Course();
ArrayList students = new ArrayList();
c.students.Add(student1);
c.students.Add(student2);
c.students.Add(student3);
foreach (Student o in c.students)
{
Student s = (Student)o;
Console.WriteLine(s.FirstName);
}
Console.ReadLine();
}
}
internal class Course
{
public ArrayList students = new ArrayList();
}
internal class Student
{
private string firstName;
private string lastName;
public Student()
{
}
public Student(string fname)
{
this.FirstName = fname;
}
public string FirstName
{
get
{
return firstName;
}
set
{
firstName = value;
}
}
public string LastName
{
get
{
return lastName;
}
set
{
lastName = value;
}
}
}
Related
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 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 was asked to create some structures: student, teacher, course, program
and then make an array to hold 5 students structures, and assign values to the fields of students in the array, I'm stuck in creating the array to hold the structures, here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Module4Assignment
{
class Program
{
//Student structure:
public struct Student
{
public Student (string name , string address , string country , string birthday , int telephone)
{
this.Name = name;
this.Address = address;
this.Country = country;
this.Birthday = birthday;
this.Telephone =telephone;
}
public string Name;
public string Address;
public string Country;
public string Birthday;
public int Telephone;
}
//Teacher structure:
public struct Teacher
{
public Teacher(string tname, string taddress, string tcountry, string tbirthday, int ttelephone)
{
this.TName = tname;
this.TAddress = taddress;
this.TCountry = tcountry;
this.TBirthday = tbirthday;
this.TTelephone = ttelephone;
}
public string TName;
public string TAddress;
public string TCountry;
public string TBirthday;
public int TTelephone;
}
//Program structure
public struct Program
{
public Program(string pname , string department , int pcredits)
{
this.PName = pname;
this.Department = department;
this.PCredits = pcredits;
}
public string PName;
public string Department;
public int PCredits;
}
//Course structure
public struct Course
{
public Course(string cname, string day, int ccredits)
{
this.CName = cname;
this.Day = day;
this.CCredits = ccredits;
}
public string CName;
public string Day;
public int CCredits;
}
static void Main(string[] args)
{
//Instantiating 5 students structures:
Student student1 = new Student();
Student student2 = new Student();
Student student3 = new Student();
Student student4 = new Student();
Student student5 = new Student();
//creating the array:
string[] studentArray = new string[5];
studentArray[0]=student1;
studentArray[1]=student2;
studentArray[2]=student3;
studentArray[3]=student4;
studentArray[4]=student5;
}
}
}
I have a lot of problems with what you're doing here, but the simple answer is that you cant put Student objects into an array of strings:
static void Main(string[] args)
{
//Instantiating 5 students structures :
Student student1 = new Student();
Student student2 = new Student();
Student student3 = new Student();
Student student4 = new Student();
Student student5 = new Student();
//creating the array :
Student [] studentArray = new Student[5]; // <---- array of Student!
studentArray[0]=student1;
studentArray[1]=student2;
studentArray[2]=student3;
studentArray[3]=student4;
studentArray[4]=student5;
}
static void Main(string[] args)
{
Student[] studentArray = new Student[5];
}
That's it. You do not need to explicitly create and assign the elements, because Student is a struct (value type).
what you did on the code above is a repetition of just creating an array of a structure because you are supposed to create 5 structures with the properties of the original structure so you should do it like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EDXonline_AssignmentFour
{
class Program
{
static void Main(string[] args)
{
student[] studentArray = new student[5];
studentArray[0].FirstName = "einstein";
studentArray[0].LastName = "makuyana";
DateTime date1 = new DateTime(1993, 11, 22, 02, 00, 0);
studentArray[0].Birthdate = date1;
Console.WriteLine("student First Name: {0}", studentArray[0].FirstName);
Console.WriteLine("student Last Name: {0}", studentArray[0].LastName);
Console.WriteLine("student birthday: {0}", studentArray[0].Birthdate.ToString());
Console.ReadKey();
}
public struct student
{
// This is the custom constructor.
public student(string firstname, string lastname, DateTime birthdate)
{
this.FirstName = firstname;
this.LastName = lastname;
this.Birthdate = birthdate;
}
// These statements declare the struct fields and set the default values.
public string FirstName;
public string LastName;
public DateTime Birthdate;
}
I have the following models:
public class Person
{
long Id;
string name;
}
public class Student : Person
{
string studentId;
}
public class Bus
{
long Id;
public ICollection<Person> riders {set; get;}
}
public class SchoolBus : Bus
{
long schoolBusNumber;
}
I also have the following code:
SchoolBus schoolBus = new SchoolBus();
schoolBus.riders = new List<Person>
{
new Student { name = "Jim" },
new Student { name = "Jane }
}
var query = from rider in SchoolBus.riders
select new
{
(rider as Student).studentId;
}
Students and Person are set up as separate tables and I'm using DbContext.
I know why this would not work, but what are possible solutions for me to get this to return the right studentId by using a Person collection?
try this:
var studentIds = rider.OfType<Student>().Select(x => x.studentId);
If your code is exactly what you shown, this will work:
SchoolBus schoolBus = new SchoolBus();
schoolBus.riders = new List<Person>
{
new Student { name = "Jim" },
new Student { name = "Jane }
}
var query = from rider in SchoolBus.riders
select new
{
riderID = (rider as Student).studentId;
}
But if your query runs on linq2entity, you should show your exact code, and your problem.