Creating new class instance in a loop - c#

I've just started learning about methods and classes, I would like to know if I can have something like,
CarsSold Day1 = new CarsSold();
in a for loop where it will create a new instance of a new day each time it runs. For example on the second time the loop runs I want it to create an instance like this,
CarsSold Day2 = new CarsSold();
I have tried to use an array but either it cant be done with arrays or I'm using the wrong syntax. Thanks in advance.
Full code
class Program
{
static void Main(string[] args)
{
int[] weekDay = new int[7];
int userInput;
int x;
for (x = 0; x < weekDay.Length; x++)
{
Console.Write("Enter the number of cars sold: ");
bool ifInt = int.TryParse(Console.ReadLine(), out userInput);
CarsSold Day[x] = new CarsSold(userInput);
}
}
}

The problem is how you're trying to define your array. The syntax is invalid, and you're doing it in the wrong place.
You should define the array before your loop, and then only assign values to the array within the loop.
static void Main(string[] args)
{
int userInput;
CarsSold[] days = new CarsSold[7]; // create an array with 7 items
int x;
for (x = 0; x < days.Length; x++)
{
Console.Write("Enter the number of cars sold: ");
bool ifInt = int.TryParse(Console.ReadLine(), out userInput);
days[x] = new CarsSold(userInput); // assign a value to the days array at position x.
}
}
Note also that arrays start from 0, not 1, so the first item is actually days[0], and the last is days[6] (for a 7-item array). I took the liberty of removing weekDays since it wasn't needed here, and replaced it in the loop with days.Length.

Arrays can have set amount of things in them, so if you declare an array like this
object[] objectArray = new object[10];
Then that array can hold only 10 objects. If you want to add anything to an array you have to chose an index to which that thing will be assigned to, for example:
objectArray[2] = "some value";
in Your case you could iterate through the array and add new object to each index like this
for (var i = 0; i < objectArray.Length; i++)
{
objectArray[i] = new YourObject();
}
If the amount of objects you want to store is unknown and can change then you should use collections, for example a List
List<object> listOfObjects = new List<object>();
Now if you want to add anything to that list you simply do
listOfObjects.Add(itemYouWantToAddToTheList);
You access lists the same way you would access arrays, so you can use indexes like
var someValue = listOfObjects[0];
As you probably noticed this list has a generic parameter <object>, it tells the list what type of data it can store, in my example its the object type so it can pretty much store anything, but you can set it to string or int or any other type like your own class types and then this list would store only those types of objects.

If you don't know the number of days, then:
IList<CarsSold> soldCarsList = new List<CarsSold>();
foreach(var day in Days)
{
soldCarsList.Add(new CarsSold());
}
If you know the number of days(e.g:7), then:
CarsSold[] soldCarsArray = new CarsSold[7];
for (int i = 0; i < days.Length; x++)
{
soldCarsArray[i] = new CarsSold();
}

Related

C# Array in array

I'm stuck trying to create array of arrays..
This is what i have for now, i would appreciate if someone could point me to right direction.
I have .txt file which has paths to images and each string has desired output separated with "|" like so:
":\\\img.png|1"
I'm trying to create array that has 2 columns and number of imagepaths as rows. Col 0 being a array of flattened rgb values of the image and col 1 being output as int.
I'm getting error from line Data[i][0] = Flat;
"Cannot implicitly convert type 'int[]' to 'int'"
It might be obvious to more experienced coders here but i cant wrap my head around this.
static int[][] CreateDataSet(string DatasetPath)
{
string[] Lines = File.ReadAllLines(DatasetPath);
int[][] Data = new int[Lines.GetUpperBound(0)][];
for (int i = 0; i <= Lines.GetUpperBound(0); i++)
{
Data[i] = new int[2];
string[] StringSplit = Lines[i].Split('|');
Data[i][1] = Convert.ToInt32(StringSplit[1]);
int[] Flat = FlattenArray(ImagetoArray(StringSplit[0]));
Data[i][0] = Flat;
}
return Data;
}
In an array, all elements must have same type (or at least must be assignable to a variable of the element's type).
You have two options.
The bad one: use array of objects.
object[][] data;
Now you can put everything in that array, but it will be slow (boxing of value types) and untyped (hard to use and to maintain).
Instead of a jagged array, use tuples.
(int[] FlattenedImage, int Output)[] data;
That looks a little bit weird, but it's actually very useful. It's strongly typed, it prevents boxing, and it uses nice and modern language features.
The big problem here is you have an int and an int[]. So the [0] index of Data must itself be an array, rather than merely an integer. And since the [0] and [1] subscripts are different types, you're really gonna need a completely different kind of data structure here.
Here's an example using Tuples:
static IEnumerable<(int, int[])> CreateDataSet(string DatasetPath)
{
var result = new List<(int, int[])> = new List<(int, int[])>();
foreach(string line in File.ReadLines(DatasetPath))
{
var lineData = line.Split('|');
yield return (int.Parse(linedata[1]), FlattenArray(ImageToArray(lineData[0])) );
}
}
or with linq:
static IEnumerable<(int, int[])> CreateDataSet(string DatasetPath)
{
return File.ReadLines(DatasetPath).Select(line => {
var data = line.Split('|');
return ( int.Parse(data[1]), FlattenArray(ImageToArray(data[0])) );
});
}
If you would create a class or a struct to containt the data it would look something like this:
class ImageData
{
public int[] FlatImate { get; }
public int Number { get; }
public ImageData(int[] flatImage, int number)
{
FlatImage = flatImage;
Number = number;
}
}
static ImageData[] CreateDataSet(string datasetPath)
{
string[] lines = File.ReadAllLines(datasetPath);
ImageData[] data = new ImageData[Lines.GetUpperBound(0)];
for (int i = 0; i <= lines.GetUpperBound(0); i++)
{
string[] stringSplit = lines[i].Split('|');
int number = Convert.ToInt32(stringSplit[1]);
int[] flat = FlattenArray(ImagetoArray(StringSplit[0]));
data[i] = new ImageData(flat, number);
}
return data;
}

C#: Why does an intermediate array need to be used for defining a jagged array?

I found a curious effect in some code I wrote that I don't understand. I found a workaround but I'd like to know why the original code doesn't work as expected.
So populating a jagged array, I tried to define each cell individually. This resulted in 10 copies of the last array defined. From this code:
for (int i = 0; i < 10; i++)
{
serialisableHighScores.scores[i][0] = _highScores[i].date;
serialisableHighScores.scores[i][1] = _highScores[i].score;
serialisableHighScores.scores[i][2] = _highScores[i].questionsAsked;
}
Whereas when using a single dimension array as an intermediate, the data saved as expected. By which I mean there were 10 unique arrays saved in the jagged array. From this code:
for (int i = 0; i < 10; i++)
{
int[] scoreArray = { _highScores[i].date, _highScores[i].score, _highScores[i].questionsAsked };
serialisableHighScores.scores[i] = scoreArray;
}
The reason is that a jagged array is actually an array of arrays of values.
Since arrays are objects, reference types, it means that if you construct a jagged array with room for 10 arrays, all those array references are initialized to null.
In other words:
int[][] a = new int[10][];
a[0][0] = 10;
throws NullReferenceException.
The code can be thought of like this:
int[][] a = new int[10][];
int[] temp = a[0]; // this works, but temp is now null
temp[0] = 10; // throws NullReferenceException
Either you assign a fully populated array into the first slot, or you assign an initialized array without the values, like this:
for (int i = 0; i < 10; i++)
{
serialisableHighScores.scores[i] = new int[3];
serialisableHighScores.scores[i][0] = _highScores[i].date;
serialisableHighScores.scores[i][1] = _highScores[i].score;
serialisableHighScores.scores[i][2] = _highScores[i].questionsAsked;
}
Now, that's just the explanation of why it crashes on your end. The best option you have available is not to use arrays like this, that is, don't use 2-dimensional arrays to keep one list of related values, instead use objects:
public class Score
{
public Score(DateTime date, int score, int questionsAsked)
{
Date = date;
Score = score;
QuestionsAsked = questionsAsked;
}
public DateTime Date { get; }
public int Score { get; }
public int QuestionsAsked { get; }
}
Additionally, arrays are good for fixed size things but in general it's usually better to use lists:
var serializableHighScores = new List<Score>();
for (int i = 0; i < 10; i++)
{
serializableHighScores.Add(new Score(_highScores[i].date, _highScores[i].score, _highScores[i].questionsAsked));
}
Though given the name of your variable, if you need to adhere to some badly designed (my opinion) serializing format with arrays of arrays it's probably better to just stick with your code.

Why "foo = new double[int x, int y]" is legal but not "foo = new double[int x][int y]"?

I know there are differences between jagged and multidimensional arrays. I know it is often likeable to use a "List<>" instead of arrays of arrays.
Could someone just explain me why, in the following code, the first is allowed but the second is an error? I just want to better understand C#...
Legal:
public class Banana
{
double[,] _banana;
public Banana(int h, int w)
{
_banana= new double[h,w];
}
}
Illegal (Error: a constant value is expected instead of h and w):
public class Banana
{
double[][] _banana;
public Banana(int h, int w)
{
_banana= new double[h][w]{};
}
}
TL;DR;
Why is it possible to initialize the dimensions of a multi array with variables but not a jagged array's?
An int[4,5] is single object which holds twenty integers. An int[4][] is an object which holds four references to integer arrays. Having int[][] foo = new int[4][5]; be equivalent to:
int[][] foo = new int[4][];
for (int temp = 0; temp < 4; temp++)
foo[i] = new int[5];
would make about as much sense as having StringBuilder bar[] = new StringBuilder[4](); be equivalent to:
StringBuilder bar = new StringBuilder[4];
for (int temp = 0; temp < 4; temp++)
bar[i] = new StringBuilder();
Such a feature might be helpful in many cases, and there wouldn't be anything particularly wrong with it conceptually, but the code required to explicitly initialize array elements isn't particularly onerous, and writing such code explicitly helps make clear that the array-of-references and the things to which those references refers are all separate entities.
With a jagged array you have to initialize each "leg" separately - there's no syntax to initialize the size of each leg in one pass:
public Banana(int h, int w)
{
_banana = new double[h][];
for (int i = 0; i < h; i++)
{
_banana[i] = new double[w];
}
}
Why is there no syntax? Because the spec doesn't require it, and in a "typical" jagged array the legs have different lengths, otherwise a 2-D array may be more appropriate.
Each nested array in a jagged array can have a different length. If you had to initialize it using your syntax example, they would all be required to have the same length. It simply doesn't make sense. You'd have to use something like:
_banana = new double[h][];
for(var i = 0; i < h; i++)
{
_banana[h] = new double[w];
}

Organize values in an array but keep items "paired together"

So for my homework assignment I need to write a type of program that has the user type in the persons name and then their score. It then needs to find the highest, lowest, and the average score and list the player that achieved each one.
static void Main()
{
string userInput;
Console.Write("Please enter bowler's first name and then a score then use a comma to seperate plays\nExample: Elliott 200,John 180,Jane 193\nPlease enter values here: ");
userInput = Console.ReadLine();
char[] delimiters = new char[] { ' ', ','};
string[] parts = userInput.Split(delimiters);
for (int i = 0; i < parts.Length; i++)
{
Console.WriteLine(parts[i]);
}
Console.ReadLine();
}//End Main()
As you can see I've figured out how to split the input, but I don't know how to organize them and pair them together. I've been looking online for an answer and have heard of lists but I've never used them. It this even possible on an array? Do I need to do this on two different arrays?
I have also tried splitting into two arrays but it has a convert issue
string userInput;
const int ZERO = 0;
const int ONE = 1;
const int TEN = 10;
string[] parsedInput = new string[TEN];
string[] name = new string[TEN];
int[] score = new int[TEN];
for (int i = 0; i < TEN; ++i)
{
Console.Write("Please enter bowler's first name and then a score\nExample: Name 200\nPlease enter values here: ", i);
userInput = Console.ReadLine();
parsedInput = userInput.Split();
name = parsedInput[ZERO];
score = int.Parse(parsedInput[ONE]);
}
When you say you don't know how to pair them together, this is what a class is for.
public class Person
{
public string Name { get; set; }
public int Score { get; set; }
}
Once you have that, you're on the right track with using a List instead of an array (not that you couldn't use arrays but this would be the preferred way)
List<Person> people = new List<Person>();
You can then use a loop to go through your list and access the properties.
foreach(Person person in people)
{
Console.WriteLine(person.Name + ", " + person.Score.ToString());
}
The other answer posted is fine, but you should probably focus on something like this first if you are just learning.
You definitely can do that using simple array of string. But I'm not going to give you code like that. You should definitely spend much more time to learn about classes, arrays, lists, loops, etc. You're not gonna learn anything unless you do it by yourself.
And just to show you, how it could be done when you know the language you're using well: LINQ one-liner to get a list of anonymous type objects, sorted descending by the value:
var items = input.Split(',')
.Select(x => x.Split(' '))
.Select(x => new { name = x[0], value = int.Parse(x[1]) })
.OrderByDescending(x => x.value)
.ToList();
And taking what you need from the list:
// min/max are items, so both .name and .value are there
var maxItem = items.First();
var minItem = items.Last();
// average is just a number
var average = items.Average(x => (double)x.value);

Adding values to a C# array

Probably a really simple one this - I'm starting out with C# and need to add values to an array, for example:
int[] terms;
for(int runs = 0; runs < 400; runs++)
{
terms[] = runs;
}
For those who have used PHP, here's what I'm trying to do in C#:
$arr = array();
for ($i = 0; $i < 10; $i++) {
$arr[] = $i;
}
You can do this way -
int[] terms = new int[400];
for (int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}
Alternatively, you can use Lists - the advantage with lists being, you don't need to know the array size when instantiating the list.
List<int> termsList = new List<int>();
for (int runs = 0; runs < 400; runs++)
{
termsList.Add(value);
}
// You can convert it back to an array if you would like to
int[] terms = termsList.ToArray();
Edit: a) for loops on List<T> are a bit more than 2 times cheaper than foreach loops on List<T>, b) Looping on array is around 2 times cheaper than looping on List<T>, c) looping on array using for is 5 times cheaper than looping on List<T> using foreach (which most of us do).
Using Linq's method Concat makes this simple
int[] array = new int[] { 3, 4 };
array = array.Concat(new int[] { 2 }).ToArray();
result
3,4,2
If you're writing in C# 3, you can do it with a one-liner:
int[] terms = Enumerable.Range(0, 400).ToArray();
This code snippet assumes that you have a using directive for System.Linq at the top of your file.
On the other hand, if you're looking for something that can be dynamically resized, as it appears is the case for PHP (I've never actually learned it), then you may want to use a List instead of an int[]. Here's what that code would look like:
List<int> terms = Enumerable.Range(0, 400).ToList();
Note, however, that you cannot simply add a 401st element by setting terms[400] to a value. You'd instead need to call Add() like this:
terms.Add(1337);
By 2019 you can use Append, Prepend using LinQ in just one line
using System.Linq;
and then in NET 6.0:
terms = terms.Append(21);
or versions lower than NET 6.0
terms = terms.Append(21).ToArray();
Answers on how to do it using an array are provided here.
However, C# has a very handy thing called System.Collections
Collections are fancy alternatives to using an array, though many of them use an array internally.
For example, C# has a collection called List that functions very similar to the PHP array.
using System.Collections.Generic;
// Create a List, and it can only contain integers.
List<int> list = new List<int>();
for (int i = 0; i < 400; i++)
{
list.Add(i);
}
Using a List as an intermediary is the easiest way, as others have described, but since your input is an array and you don't just want to keep the data in a List, I presume you might be concerned about performance.
The most efficient method is likely allocating a new array and then using Array.Copy or Array.CopyTo. This is not hard if you just want to add an item to the end of the list:
public static T[] Add<T>(this T[] target, T item)
{
if (target == null)
{
//TODO: Return null or throw ArgumentNullException;
}
T[] result = new T[target.Length + 1];
target.CopyTo(result, 0);
result[target.Length] = item;
return result;
}
I can also post code for an Insert extension method that takes a destination index as input, if desired. It's a little more complicated and uses the static method Array.Copy 1-2 times.
Based on the answer of Thracx (I don't have enough points to answer):
public static T[] Add<T>(this T[] target, params T[] items)
{
// Validate the parameters
if (target == null) {
target = new T[] { };
}
if (items== null) {
items = new T[] { };
}
// Join the arrays
T[] result = new T[target.Length + items.Length];
target.CopyTo(result, 0);
items.CopyTo(result, target.Length);
return result;
}
This allows to add more than just one item to the array, or just pass an array as a parameter to join two arrays.
You have to allocate the array first:
int [] terms = new int[400]; // allocate an array of 400 ints
for(int runs = 0; runs < terms.Length; runs++) // Use Length property rather than the 400 magic number again
{
terms[runs] = value;
}
int ArraySize = 400;
int[] terms = new int[ArraySize];
for(int runs = 0; runs < ArraySize; runs++)
{
terms[runs] = runs;
}
That would be how I'd code it.
C# arrays are fixed length and always indexed. Go with Motti's solution:
int [] terms = new int[400];
for(int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}
Note that this array is a dense array, a contiguous block of 400 bytes where you can drop things. If you want a dynamically sized array, use a List<int>.
List<int> terms = new List<int>();
for(int runs = 0; runs < 400; runs ++)
{
terms.Add(runs);
}
Neither int[] nor List<int> is an associative array -- that would be a Dictionary<> in C#. Both arrays and lists are dense.
You can't just add an element to an array easily. You can set the element at a given position as fallen888 outlined, but I recommend to use a List<int> or a Collection<int> instead, and use ToArray() if you need it converted into an array.
If you really need an array the following is probly the simplest:
using System.Collections.Generic;
// Create a List, and it can only contain integers.
List<int> list = new List<int>();
for (int i = 0; i < 400; i++)
{
list.Add(i);
}
int [] terms = list.ToArray();
one approach is to fill an array via LINQ
if you want to fill an array with one element
you can simply write
string[] arrayToBeFilled;
arrayToBeFilled= arrayToBeFilled.Append("str").ToArray();
furthermore, If you want to fill an array with multiple elements you can use the
previous code in a loop
//the array you want to fill values in
string[] arrayToBeFilled;
//list of values that you want to fill inside an array
List<string> listToFill = new List<string> { "a1", "a2", "a3" };
//looping through list to start filling the array
foreach (string str in listToFill){
// here are the LINQ extensions
arrayToBeFilled= arrayToBeFilled.Append(str).ToArray();
}
Array Push Example
public void ArrayPush<T>(ref T[] table, object value)
{
Array.Resize(ref table, table.Length + 1); // Resizing the array for the cloned length (+-) (+1)
table.SetValue(value, table.Length - 1); // Setting the value for the new element
}
int[] terms = new int[10]; //create 10 empty index in array terms
//fill value = 400 for every index (run) in the array
//terms.Length is the total length of the array, it is equal to 10 in this case
for (int run = 0; run < terms.Length; run++)
{
terms[run] = 400;
}
//print value from each of the index
for (int run = 0; run < terms.Length; run++)
{
Console.WriteLine("Value in index {0}:\t{1}",run, terms[run]);
}
Console.ReadLine();
/*Output:
Value in index 0: 400
Value in index 1: 400
Value in index 2: 400
Value in index 3: 400
Value in index 4: 400
Value in index 5: 400
Value in index 6: 400
Value in index 7: 400
Value in index 8: 400
Value in index 9: 400
*/
If you don't know the size of the Array or already have an existing array that you are adding to. You can go about this in two ways. The first is using a generic List<T>:
To do this you will want convert the array to a var termsList = terms.ToList(); and use the Add method. Then when done use the var terms = termsList.ToArray(); method to convert back to an array.
var terms = default(int[]);
var termsList = terms == null ? new List<int>() : terms.ToList();
for(var i = 0; i < 400; i++)
termsList.Add(i);
terms = termsList.ToArray();
The second way is resizing the current array:
var terms = default(int[]);
for(var i = 0; i < 400; i++)
{
if(terms == null)
terms = new int[1];
else
Array.Resize<int>(ref terms, terms.Length + 1);
terms[terms.Length - 1] = i;
}
If you are using .NET 3.5 Array.Add(...);
Both of these will allow you to do it dynamically. If you will be adding lots of items then just use a List<T>. If it's just a couple of items then it will have better performance resizing the array. This is because you take more of a hit for creating the List<T> object.
Times in ticks:
3 items
Array Resize Time: 6
List Add Time: 16
400 items
Array Resize Time: 305
List Add Time: 20
I will add this for a another variant. I prefer this type of functional coding lines more.
Enumerable.Range(0, 400).Select(x => x).ToArray();
You can't do this directly. However, you can use Linq to do this:
List<int> termsLst=new List<int>();
for (int runs = 0; runs < 400; runs++)
{
termsLst.Add(runs);
}
int[] terms = termsLst.ToArray();
If the array terms wasn't empty in the beginning, you can convert it to List first then do your stuf. Like:
List<int> termsLst = terms.ToList();
for (int runs = 0; runs < 400; runs++)
{
termsLst.Add(runs);
}
terms = termsLst.ToArray();
Note: don't miss adding 'using System.Linq;' at the begaining of the file.
This seems like a lot less trouble to me:
var usageList = usageArray.ToList();
usageList.Add("newstuff");
usageArray = usageList.ToArray();
Just a different approach:
int runs = 0;
bool batting = true;
string scorecard;
while (batting = runs < 400)
scorecard += "!" + runs++;
return scorecard.Split("!");
int[] terms = new int[400];
for(int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}
static void Main(string[] args)
{
int[] arrayname = new int[5];/*arrayname is an array of 5 integer [5] mean in array [0],[1],[2],[3],[4],[5] because array starts with zero*/
int i, j;
/*initialize elements of array arrayname*/
for (i = 0; i < 5; i++)
{
arrayname[i] = i + 100;
}
/*output each array element value*/
for (j = 0; j < 5; j++)
{
Console.WriteLine("Element and output value [{0}]={1}",j,arrayname[j]);
}
Console.ReadKey();/*Obtains the next character or function key pressed by the user.
The pressed key is displayed in the console window.*/
}
/*arrayname is an array of 5 integer*/
int[] arrayname = new int[5];
int i, j;
/*initialize elements of array arrayname*/
for (i = 0; i < 5; i++)
{
arrayname[i] = i + 100;
}
To add the list values to string array using C# without using ToArray() method
List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");
list.Add("four");
list.Add("five");
string[] values = new string[list.Count];//assigning the count for array
for(int i=0;i<list.Count;i++)
{
values[i] = list[i].ToString();
}
Output of the value array contains:
one
two
three
four
five
You can do this is with a list. here is how
List<string> info = new List<string>();
info.Add("finally worked");
and if you need to return this array do
return info.ToArray();
Here is one way how to deal with adding new numbers and strings to Array:
int[] ids = new int[10];
ids[0] = 1;
string[] names = new string[10];
do
{
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine("Enter Name");
names[i] = Convert.ToString(Console.ReadLine());
Console.WriteLine($"The Name is: {names[i]}");
Console.WriteLine($"the index of name is: {i}");
Console.WriteLine("Enter ID");
ids[i] = Convert.ToInt32(Console.ReadLine());
Console.WriteLine($"The number is: {ids[i]}");
Console.WriteLine($"the index is: {i}");
}
} while (names.Length <= 10);

Categories

Resources