I am not sure if multidimensional arrays would be the correct thing for what I want to do.
I want to input the amount of students and then for each of them I input 5 grades. After doing so I must calculate the average.
So essentially something like this:
Student..........Grade 1......Grade 2......Grade 3......Grade 4......Grade 5......Average
Student1............87..............71................64...............89...............78..............77.8
Student2............54..............76................89...............89...............78..............77.2
I apologise for the formatting. I don't know block quotes to well.
I am not sure if multidimensional arrays would help. Any Ideas.
what you can do is to create a Student class and make an array of Student e.g.
public class Student
{
private ArrayList grades;
public Student()
{
grades = new ArrayList();
}
public void addGrade(double val)
{
grades.Add(val);
}
public double getAverage()
{
double avg = 0;
for (int i = 0; i < grades.Count; i++)
avg += (double)grades[i];
avg /= grades.Count;
return avg;
}
}
and make an array of Student class as:
Student [] students = new Student[10];
add student grades as:
students[0].addGrade(75);
Since the datatype of a student's name is probably a string and the datatype of a student's grades is probably a list of double, I recommend you start with a class that represents a single student. Then, as you gather one student's data from a form, you can create a student object, load the object with data from a form, then calculate the average grade for the student. I'm not sure if you need to do anything with the student object after that (i.e., add it to a list for export, write it to a database, etc., etc.)
The code below only suggests what the student class might look like.
using System.Collections.Generic;
using System.Windows.Forms;
namespace sandbox
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
class Student
{
string studentFirstMiddleLastName;
IList<double> allStudentGrades = new List<double>();
public Student(string studentFirstMiddleLastName, IList<double> allStudentGrades)
{
StudentFirstMiddleLastName = studentFirstMiddleLastName;
AllStudentGrades = allStudentGrades;
}
public string StudentFirstMiddleLastName { get => studentFirstMiddleLastName; set => studentFirstMiddleLastName = value; }
public IList<double> AllStudentGrades { get => allStudentGrades; set => allStudentGrades = value; }
public double CalculateAverageofAllStudentGrades()
{
double average = 0.0;
// add up all grades in AllStudentGrades, divide by number of items in AllStudentGrades, load result of this calculation into the variable `average`
return average;
}
}
}
Related
I am having some trouble in querying an object array using LINQ. I want to retrieve all products that contains the value passed.
My Product class
public class Product
{
public int mProductId;
public string mProductName;
public string mProductColor;
public string mProductSize;
public string mProductStatus;
public string mProductCode;
public int ProductId{ get { return mProductId; }}
public string ProductName { get{return mProductName; }}
public string ProductColor { get{return mProductColor;} }
public string ProductSize { get{return mProductSize;} }
public string ProductStatus { get{return mProductStatus;} }
public string ProductCode {get { return mProductCode; }}
}
public class ProductList
{
public static Product[] mProductList = {
new Product { mProductId = Resource.Drawable.Product1,
mProductName = "Green Lumberjack Cap",
mProductColor = "Color Brown",
mProductSize = "One Size Fits All",
mProductCode= "9780201760439",
mProductStatus= "In Stock"},
new Product { mProductId = Resource.Drawable.Product2,
mProductName = "Square Bar stool",
mProductColor= "Color Brown",
mProductSize = "One Size Fits All",
mProductCode= "9780201760440",
mProductStatus= "In Stock"},
new Product { mProductId = Resource.Drawable.Product3,
mProductName = "Vitra bathroom Tile",
mProductColor= "Color Brown",
mProductSize = "One Size Fits All",
mProductCode= "9780201760539",
mProductStatus= "In Stock"},
};
private Product[] mProducts;
Random mRandom;
public ProductList ()
{
mProducts = mProductList;
}
// Return the number of photos in the photo album:
public int NumPhotos
{
get { return mProducts.Length; }
}
// Indexer (read only) for accessing a photo:
public Product this[int i]
{
get { return mProducts[i]; }
}
// Pick a random photo and swap it with the top:
public int RandomSwap()
{
// Save the photo at the top:
Product tmpProduct = mProducts[0];
// Generate a next random index between 1 and
// Length (noninclusive):
int rnd = mRandom.Next(1, mProducts.Length);
// Exchange top photo with randomly-chosen photo:
mProducts[0] = mProducts[rnd];
mProducts[rnd] = tmpProduct;
// Return the index of which photo was swapped with the top:
return rnd;
}
// Shuffle the order of the photos:
public void Shuffle ()
{
// Use the Fisher-Yates shuffle algorithm:
for (int idx = 0; idx < mProducts.Length; ++idx)
{
// Save the photo at idx:
Product tmpProduct = mProducts[idx];
// Generate a next random index between idx (inclusive) and
// Length (noninclusive):
int rnd = mRandom.Next(idx, mProducts.Length);
// Exchange photo at idx with randomly-chosen (later) photo:
mProducts[idx] = mProducts[rnd];
mProducts[rnd] = tmpProduct;
}
}
}
and my LINQ statement is
var result = from p in nProductList<Product>
where ( p.mProductName.Contains(query) || p.mProductColor.Contains(query))
select p;
I have also declared nProductList in my class as
public ProductList nProductList;
It will be really great to know what am I doing wrong.
Thank you
In order to get the where keyword syntax to work, your ProductList class must have a Where(Func<Product, bool>) method on it. Most lists get this automatically because they implement IEnumerable<>, and the System.Linq namespace has a Where() extension method which matches this signature.
You could make ProductList implement the IEnumerable<Product> interface, or make it extend a class like List<Product> which already implements that interface, or add your own Where() method. However, I'd personally suggest that you just expose mProductList as an IEnumerable<Product> via a public property getter, and change your consuming code to query against that.
The reason why your linq statement does not work is because you did not define where. Imagine the old style linq:
nProductList.Where(p=>p.mProductName.Contains(query) || p.mProductColor.Contains(query)).Select(p=>);
nProductList does not have Where(Func) defined so it does not work.
Normally for your ProductList there are two ways to implement. First way is to inherit from IEnumerable<Product> as ProductList : IEnumerable<Product>;
Second way is to create a member in ProductList and make it public like
public class ProductList
{
public IEnumerable<Product> Products {get; private set;}
...
}
Usually the preferable way between the two above will depends on is there more properties or more methods in your ProductList class. More methods goes to the first way because it's more like an expended method collection of IEnumerable class (like your example), while more properties goes to the seconding way as this is more like another class just having a list in it and something else.
Hey I have an array of structs and i need to create in program way to change the values of the arrays. I tried using things like findindex but it replaced all values (e.g changed all of Mark's into Jack's even though i only want the one specific "Mark" to change.)
What i want to do is make user type the customer number and then change all the values of this array. So if i search and want to edit customernumber[0] i can also change all other values like customersurname[0], customerfornemae[0] and so on. I am posting only the parts of code i think are important but if you guys need any more I' can easily provide.
struct customer
{
public int customernumber;
public string customersurname;
public string customerforname;
public string customerstreet;
public string customertown;
public DateTime customerdob;
}
static void Main(string[] args)
{
customer[] customerdetails = new customer[99];
int selector = 0;
int selector2 = 0;
string vtemp = "";
string ctemp = "";
int searchnumber;
int updatenumber;
string searchforename;
string searchsurname;
string searchtown;
DateTime searchdob;
customer resultnumber;
customer resultforename;
customer resultsurname;
customer resulttown;
customer resultdob;
customer updaterenumber;
if (selector == 3)
{
Console.Clear();
Console.WriteLine("Enter the customer number you wish to update: ");
updatenumber = int.Parse(Console.ReadLine());
updaterenumber = Array.Find(customerdetails, customer => customer.customernumber == updatenumber);
}
I have tried to add 2 types of objects in an Array List and then have tried to display them but somehow it is not working. Do I need to use 2 Array List objects or how is it going to work?
Error Message:
Unable to cast object of type 'ArrayList_Practice.Student' to type
'ArrayList_Practice.Employees'.
class Program
{
static void Main(string[] args)
{
Student st=null;
Employees emp = null;
ArrayList al = new ArrayList();
Console.WriteLine("Enter Records");
for (int i = 0; i < 2; i++)
{
st = new Student();
Console.WriteLine("Enter roll");
st.roll = int.Parse(Console.ReadLine());
Console.WriteLine("Enter name");
st.name = Console.ReadLine();
Console.WriteLine("Enter course");
st.course = Console.ReadLine();
al.Add(st);
emp = new Employees();
Console.WriteLine("Enter empID");
emp.empID = int.Parse(Console.ReadLine());
Console.WriteLine("Enter name");
emp.name = Console.ReadLine();
al.Add(emp);
}
Console.WriteLine("/////////////Show Records//////////");
for (int i = 0; i < 2; i++)
{
Console.WriteLine("Roll "+((Student)al[i]).roll.ToString());
Console.WriteLine("Name "+((Student)al[i]).name);
Console.WriteLine("Course "+((Student)al[i]).course);
Console.WriteLine("EmpID "+((Employees)al[i]).empID.ToString());
Console.WriteLine("EmpName "+((Employees)al[i]).name);
}
Console.ReadKey();
}
}
class Student
{
public int roll{ get; set;};
public string name{ get; set;};
public string course{ get; set;};
}
class Employees
{
public int empID{ get; set;};
public string name{ get; set;};
}
}
Your first element is a Student, and you are trying to cast it to Employee on first iteration in the loop.That's why you are getting an InvalidCastException in run-time.Don't use ArrayLists, use strongly-typed generic collections instead.For ex: List<T>.
If you want to display common properties and you want to store Students and Employees into the same list, you can create a common interface for them and implement it.Then you can have a List<CommonInterface> and store your instances.But if you have different properties (it seems you have) you can't access them using common interface or base class,instead you can simply create an extension method and use Reflection to display all property values like this:
public static class Extensions
{
public static string DisplayPerson<T>(this T source)
{
if(source == null) throw new ArgumentNullException("source");
var flags = BindingFlags.Instance | BindingFlags.Public;
var properties = source.GetType().GetProperties(flags);
if (properties.Any())
{
StringBuilder sb = new StringBuilder();
foreach (var prop in properties)
{
sb.AppendFormat("{0} : {1}", prop.Name, prop.GetValue(source));
sb.AppendLine();
}
return sb.ToString();
}
return string.Empty;
}
}
Then just call it from the loop:
for (int i = 0; i < al.Count; i++)
{
Console.WriteLine(al[i].DisplayPerson());
}
Edit: Another way using common interface
public interface IPerson
{
string Name { get; set; }
int Id { get; set; }
}
class Student : IPerson
{
/* implement the properties */
}
class Employees : IPerson
{
/* implement the properties */
}
static void Main(string[] args)
{
List<IPerson> personList = new List<IPerson>();
personList.Add(new Student {/* set properties */});
personList.Add(new Employee {/* set properties */});
// use a loop and display your properties without casting
}
in your array list, your 0th element is a student type and 1st element is an employee type.
in your loop, then you're trying to cast your 0th element to an employee to display empID.
hence you need to be aware of this..
you need to do proper cast check for the loop to work.
check if the element is student or employee and display accordingly.
for (int i = 0; i < al.Count; i++)
{
var student = al[i] as Student;
if (student != null)
{
Console.WriteLine("Roll "+ student.roll.ToString());
Console.WriteLine("Name "+ student.name);
Console.WriteLine("Course "+ student.course);
}
else
{
var employee = al[i] as Employee;
if (employee != null)
{
Console.WriteLine("EmpID "+ employee.empID.ToString());
Console.WriteLine("EmpName "+ employee.name);
}
}
}
though this works for your problem, in general you should be using strongly types collections.
e.g. List<Student> and List<Employee>
You need two lists, because you are trying to store two different types of objects in the array. While it's possible to manage this, you'd be better off keeping it simple: have an array for students and an array for employees.
I'm not sure why you enter the student and employee records at the same time, in pairs. Are the employees connected to the students in some way? Are the students employees? If so, you'd be better off creating a single object that represents student-employee, or whatever the relationship is, and filling a single list with items of that type.
Also, it's 2014 and you shouldn't be using ArrayList. At the very least, use List<>.
Here is my dictionary code.
int numOfPlayers;
double multiplier;
Dictionary<string, Stats> games = new Dictionary<string, Stats>();
games.Add("Runescape", new Stats(1.5, 20));
games.Add("Maplestory", new Stats(1.0, 25));
games.Add("League of Legends", new Stats(1.3, 15));
Here is my stats class
class Stats
{
public double Muliplier { get; private set; }
public int NumberOfPlayers { get; private set; }
public Stats(double multiplier, int numberOfPlayers)
{
Muliplier = multiplier;
NumberOfPlayers = numberOfPlayers;
}
}
Since I don't really know much about dictionaries, how do I use it so I can set the value of my variables in the class based on what the user selected in the combo box?
Ex: If the user selects "Runescape" it would help me set the value of numOfPlayers to 20 and multiplier to 1.5.
You can get data from Dictionary using array-like indexer access:
string name = "Runescape";
Stats stat = games[name];
However, it will throw an exception when no item associated with given name exists. You can make it handle that kind of cases using TryGetValue:
Stats stat;
if(games.TryGetValue(name, out stat))
{
// stat found within the dictionary
}
I've been searching the internet and books but have had no luck so was hoping someone could point me in the right direction.
I basically need to sort objects by their name statement alphabetically using an insertion sort rather than the built in methods. I have tried using an Array and List but can't seem to get it to work. How would you go about doing it?
I have a class of Player, latest attempt filled with list objects:
public static List<Player> user = new List<Player>();
private string name; //Read and Write
private int score; //Read and Write
private double health; //Read and Write
private int level; //Read and Write
public string[] inventory = new string[30];
public void setName(String newName)
{
name = newName;
}
public string getName()
{
return name;
}
public void setScore(int newScore)
{
score = newScore;
}
public int getScore()
{
return score;
}
public void setHealth(double newHealth)
{
health = newHealth;
}
public double getHealth()
{
return health;
}
public void setLevel(int newLevel)
{
level = newLevel;
}
public int getLevel()
{
return level;
}
public static void Saved_Player()
{
user.Add(new Player() { name = "Timid Bob", health = 63, level = 6, score = 2000, });
user[0].inventory[0] = "Steel Sword";
user[0].inventory[1] = "1mm MAW";
user[0].inventory[2] = "Short Bow";
user[0].inventory[0] = "Grenade";
user.Add(new Player() {name = "Killer Bob", health = 82, level = 2, score = 1050000, });
user[1].inventory[0] = "Glass Sword";
user[1].inventory[1] = "250mm MAW";
user[1].inventory[2] = "Elephant Bow";
user[1].inventory[3] = "Rock";
etc... upto 6 user objects
To sort it I'm trying to use the following code in another class Form1:
//sudo code
for(int i = 0; i < Player.user.Count; i++)
{
while (i index is higher than i+1 index)
{
swap i index with i+1 index
}
}
Hope that is right :/
I think I understand how PublicJoe's has done it but how do you get and set the index of an object? Thanks for looking.
Arrays are bad for inserting into. if you think back to your classes, you might find a data structure that works better for inserting.
In an insertion sort, you take an item of your unsorted list, and then put it in the correct spot of the other list.
What you seem to be trying to do, appears to be some sort selection sort.
I think there's a problem with the 4 lines where you swap your values
object temp;
object = Player.user[Second];
Player.user[first] = Player.user[Second];
Player.user[(temp - 1)] = Player.user[Second];
I'd have a second look at that if i were you.
If you're using a list, you can simply do this:
public void InsertionSort(Player newUser)
{
var index = users.FindLastIndex(u => u.Name <= newUser.Name);
users.Insert(index, newUser);
}