Storing info from a database in an array [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Hi I need to work out the average of 10 integers stored in a database.
This is what I've got so far.
private void getAverage()
{
StudentsDataSet.StudentsRow courseMarks = studentsDataSet.Students.Course[10];
average = 0;
int[] array;
for (int index = 0; index < 10 ; index++)
{
average += array[index];
}
average = average / 10;
averageBox.Text = average.ToString();
}
As you can see I have no idea what I'm doing... any pointers??

There are a couple of issues with your code, which I will address one by one:
You are always getting the data from row 11 of your data table (studentsDataSet.Students.Course[10]). That's probably not what you want.
You are declaring your array but you are not initializing it.
You need to fill the array before you loop over it.
You are repeating the number of courses (10) in many places in your code (e.g. the for loop and the divisor of the average). This will be a source of errors when the number of courses changes.
Be careful to choose good names for your variables. average should be sum (that's what it actually stores) and array is a poor choice, because it does not describe the content of the variable, but its format.
According to the C# naming convention methods are in PascalCase.
Here is some code that will do the job. I have added comments to explain exactly what is happening:
//The method that will add the average to the text box. You need to provide the row index.
//One common way to get the row index would be the SelectedIndex of your data grid
private void GetAverage(int rowIndex)
{
//Get the row whose data you want to process
DataRow courseMarks = studentsDataSet.Students.Rows[rowIndex];
//Initialize an array with the names of the source columns
string[] courseColumnNames = { "Course1", "Course2", "Course3", "Course4", "Course5",
"Course6", "Course7", "Course8", "Course9", "Course10" };
//Declare and initialize the array for the marks
int[] markValues = new int[courseColumnNames.Length];
//Fill the array with data
for (int index = 0; index < courseMarks.Length ; index++)
{
//Get the column name of the current course
string columnName = courseColumnNames[index];
//Copy the column value into the array
markValues[index] = (int)courseMarks[columnName];
}
//Calculate the sum
int sum = 0;
for (int index = 0; index < courseMarks.Length ; index++)
{
sum += markValues[index];
}
//Calculate the average from the sum
//Note: Since it's an integer division there will be no decimals
int average = sum / courseMarks.Length;
//Display the data
averageBox.Text = average.ToString();
}
Note that of course you could merge the two loops into one (and even drop the array, since you could just directly add to the sum variable). I have not done that to keep every step of the process clearly separated. You could also use the LINQ method Average, but that would quite miss the point here.

Instead of all your codes, you may try this:
private double GetAverage()
{
StudentsDataSet.StudentsRow courseMarks = studentsDataSet.Students.Course[10];
var average=courseMarks.Average(x =>(double) x["*YourDataColumnName*"]);
return average;
}
Where YourDataColumnName is the column of your row which contains the value you want to get average of that

You could do the following :
int average = studentsDataSet.Students.Course.Average();
You would have to add using System.Linq; for this to work.

Related

How would you create these arrays? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have got a "project" where I am only allowed to use arrays. In this project, I have to read data from a txt file then for example find the second-best lap time among runners and etc.
I can always calculate the correct answer, but I am not sure about my array management.
As you know, in C# you have to provide the length of the array at initialization. Since there are tasks where I don't know the size of the array what I did was declare a far bigger array then use this function:
private static string[] ArraySimplyfier(string[] strs, int index)
{
string[] returnStr = new string[index];
for (int i = 0; i < returnStr.Length; i++)
{
returnStr[i] = strs[i];
}
return returnStr;
}
As you can see it "clears" the nulls from the array, but the thing is I have to create it for every type of array which is not ideal. Do you have any other ideas for my problem?
Creating new, bigger arrays and copying is the way to go. You are on the right track there. This is basically what List is doing under the hood (in an optimized way).
If you need this for multiple types, you could look into generic methods. Generics allow you to specify classes and methods for multiple types.
A List will double in size when it gets too small, you can do the same. Check the "Add/EnsureCapacity" implementation for List on github.
// Adds the given object to the end of this list. The size of the list is
// increased by one. If required, the capacity of the list is doubled
// before adding the new element.
//
public void Add(T item) {
if (_size == _items.Length) EnsureCapacity(_size + 1);
_items[_size++] = item;
_version++;
}
// Ensures that the capacity of this list is at least the given minimum
// value. If the currect capacity of the list is less than min, the
// capacity is increased to twice the current capacity or to min,
// whichever is larger.
private void EnsureCapacity(int min) {
if (_items.Length < min) {
int newCapacity = _items.Length == 0? _defaultCapacity : _items.Length * 2;
// Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow.
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast
if ((uint)newCapacity > Array.MaxArrayLength) newCapacity = Array.MaxArrayLength;
if (newCapacity < min) newCapacity = min;
Capacity = newCapacity;
}
}
So your question seems to be "when filtering an array, how do I know the number of elements on beforehand, to get the size of the target array?" - you don't.
Either loop twice over the source array, once to get the count and then do the copy, or start with an equally sized array, keep the count and truncate the array by copying it to a new one with the size capped to the number of results.
You can use generics. That way u have one method for every array type.
Your method would look like this:
private static T[] ArraySimplyfier<T>(T[] array, int index)
{
T[] result = new T[index];
for (int i = 0; i < result.Length; i++)
{
result[i] = array[i];
}
return result;
}
and u can call this method like this:
//example for a string array
ArraySimplyfier<string>(new string[45], 17); //replace 'new string[45]' with your array

Fill an array with unique random integers [duplicate]

This question already has answers here:
Randomize a List<T>
(28 answers)
Closed 5 years ago.
I want to fill a small array with unique values from a bigger array. How do I check the uniqueness?
Here's what I have:
int[] numbers45 = new int[45];
for (int i = 0; i <= 44; i++) // I create a big array
{
numbers45[i] = i + 1;
}
Random r = new Random();
int[] draw5 = new int[5]; //new small array
Console.WriteLine("The 5 draws are:");
for (int i = 1; i <= 4; i++)
{
draw5[i] = numbers45[r.Next(numbers45.Length)]; //I fill the small array with values from the big one. BUT the values might not be unique.
Console.WriteLine(draw5[i]);
}
There are multiple ways to do what you are asking.
First off, though, I would recommend to use one of the classes which wraps the array type and adds some extra functionality you could use (in this case a List would probably be a perfect structure to use)!
One way to handle this is to check if the value is already in the draw5 array. This can be done with (for example) the List<T>.Contains(T) function, and if it exists, try another.
Personally though, I would probably have randomized the first array with the OrderBy linq method and just return a random number, like:
numbers45.OrderBy(o => random.Next());
That way the numbers are already random and unique when it is supposed to be added to the second list.
And a side note: Remember that arrays indexes starts on index 0. In your second loop, you start at 1 and go to 4, that is, you wont set a value to the first index.
You could just run for (int i=0;i<5;i++) to get it right.
Inspired by Jite's answer, I changed to use Guid to randomize the numbers
var randomized = numbers45.OrderBy(o => Guid.NewGuid().ToString());
Then you could take the draws by:
var draws = randomized.Take(5).ToArray;
HashSet<int> hs = new HashSet<int>();
int next = random.next(45);
while(hs.Length <=5)
{
if(!hs.Contains(array[next]))
hs.Add(array[next]);
next = random next(45);
}

Cannot implicitly convert type 'int' to 'string' .I can't [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have a simple question. dizi is an array of strings. I can't sort it numerically for int.
I want to sort as number array.
string[] dizi = new string[40];
for (int i = 0; i < listBox1.Items.Count; i++) {
dizi[i] = listBox1.Items[i].ToString();
}
Array.Sort(dizi);
label2.Text = dizi[0];
I think what you want is to sort the listbox items by putting them into an Array, but at the same time, you also have changed the listbox items into array of string and string cannot be sorted by descending/ascending as int does
In that case, you should rather get your listbox items as Array of int and then sort it as int before displaying it in your Label as string
int[] dizi = new int[listBox1.Items.Count]; //here is int array instead of string array, put generic size, just as many as the listBox1.Items.Count will do
for (int i = 0; i < listBox1.Items.Count; i++) {
dizi[i] = Convert.ToInt32(listBox1.Items[i].ToString());
//assuming all your listBox1.Items is in the right format, the above code shall work smoothly,
//but if not, use TryParse version below:
// int listBoxIntValue = 0;
// bool isInt = int.TryParse(listBox1.Items[i].ToString(), out listBoxIntValue); //Try to parse the listBox1 item
// if(isInt) //if the parse is successful
// dizi[i] = listBoxIntValue; //take it as array of integer element, rather than string element. Best is to use List though
//here, I put the safe-guard version by TryParse, just in case the listBox item is not necessarily valid number.
//But provided all your listBox item is in the right format, you could easily use Convert.ToInt32(listBox1.Items[i].ToString()) instead
}
Array.Sort(dizi); //sort array of integer
label2.Text = dizi[0].ToString(); //this should work
This way, dizi would be a sorted version of you listbox1 items as int. Whenever you need this as string just use ToString() for the array element
Also, as a side note: consider of using List of int and int.TryParse to get the integer element value from the listBox.Items in case you are not sure if all the listBox.Items can be converted to int for one reason or another.
Convert to ints as you remove from the list box
int[] dizi = new int[40];
for (int i = 0; i < listBox1.Items.Count; i++) {
dizi[i] = Convert.toInt32(listBox1.Items[i].ToString());
}
Array.Sort(dizi);
label2.Text= Convert.toString(dizi[0]);

C# Console Application program to Create a user defined matrix and find Lowest number [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Write a C# Console Application program to Create a user defined matrix which takes no of rows & columns and values
& find lowest number & it accept only numeric if user enter other than numeric it warn user to enter numeric only.
For Ex:
Enter no of Rows: (system)
2(user)
Enter no of Columns: (system)
2(user),
Enter row value1: 20
Enter row value 2: 4
Enter column value1: 30
Enter column value2: 20
Lowest number is: 4
please help me how to solve this ex.
Put this outside your "main" method to get make sure the user gives a number.
private static int GetNumber(string request)
{
bool succeeded = false;
Console.WriteLine(request);
string reply="";
while(!succeeded)
{
reply = Console.ReadLine();
try
{
int.Parse(reply);//Attempt to convert "reply" into an integer.
succeeded = true;
}
catch
{
Console.WriteLine(request+" (make it a number)");
}
}
return int.Parse(reply);
}
And then use this for your main method.
public static void Main()
{
int rows = GetNumber("Enter no of Rows:");
int columns = GetNumber("Enter no of Columns:");
int[,] matrix = new int[rows,columns];
for(int row = 0; row < rows; row++)
{
for (int column = 0; column < columns; column++)
{
matrix[row,column] = GetNumber("Enter value for sector Row: "+(row+1)+" Column: "+(column+1));
}
}
int smallestnumber = matrix[0,0];
for(int row = 0; row < rows; row++)
{
for (int column = 0; column < columns; column++)
{
if(matrix[row,column] < smallestnumber)
{
smallestnumber = matrix[row,column];
}
}
}
Console.WriteLine("Lowest number is: "+smallestnumber);
}
I took a liberty here as your example says "Enter row value 1...Enter column value 2" however each individual value in a matrix would be represented by both a row and a column.
Well you didn't indicate a specific part you were having trouble with but it seems checking user input for int could be tricky. Here's what I did to check if user inputted value is a number:
string row;
Console.WriteLine("Enter number of rows");
while (Int32.TryParse(Console.ReadLine(), out row) == false)
{
Console.WriteLine("Please enter a numeric value");
}
Console.WriteLine("You selected {0} rows", row);
I would also use something like a generic list of type int instead of a matrix since you don't know at the beginning how many elements the array will contain. A generic list allows you to add items to the list with no issue and you can even use
int max = MyList.Min();
to find the lowest number which is super easy.
First you have to a create matrix which takes the dynamic value; then takes two for loops: i,j; then take one temparary varible; stores the first value in the given array and then compares all the values in the array to the temp variable.

How to calculate daily total? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i have this code and its working but i want it to return dailyTotals list with four values, at the moment it is being returned with three values ... i cant seem to figure out how to make it return dailyTotals with four values. BTW the billTotals and dateList are of the same lengh which is currently 7 and they will grow. billTotals and dateList will always remain the same length
List<double> dailyTotals = new List<double>();
string dateValue = "";
double oneDayTotal = 0;
int n = 0;
for (int i = 0; i < billTotals.Count; i += n)
{
dateValue = dateList[i];
oneDayTotal = 0;
while (dateValue == dateList[n])
{
oneDayTotal += billTotals[n];
n++;
}
dailyTotals.Add(oneDayTotal);
}
return dailyTotals;
[EDIT]: Im sorry i should have written this before :/
in the database i have billTotals and the date for each bill stored. so, one date can have multiple bills associated with it. what im trying to do is grab one months data and sum the totals for each day. so the logic i used in the while loop is supposed to sum up the totals while the date is the same ... i hope this makes the scenario more clear. :)
You never reset n, so you are increasing i by increasingly large amount, skipping over some numbers.
You need to set n = 0 inside the loop.
int n = 0;
for (int i = 0; i < billTotals.Count; i += n)
{
dateValue = dateList[i];
oneDayTotal = 0;
n = 0; // This counts the number of equal dates.
while (i + n < dateList.Length && dateValue == dateList[i + n])
{
oneDayTotal += billTotals[i + n];
n++;
}
dailyTotals.Add(oneDayTotal);
}
return dailyTotals;
You could also rewrite the code entirely to simplify it and avoid this curious way of incrementing your loop variable. I would suggest creating an array of objects that hold both the date and the total, then you can use LINQ to solve your problem without any complex loops:
var dailyTotals = datesAndTotals
.GroupBy(x => x.Date)
.Select(g => g.Sum(x => x.BillTotal))
.ToList();
You can also use Zip instead of creating a separate class, though it will be more readable with the class.

Categories