How can I append values in a C# array? [duplicate] - c#

This question already has answers here:
Adding values to a C# array
(26 answers)
Add new item in existing array in c#.net
(20 answers)
Closed 5 years ago.
I need to add values to my array one integer value at a time, via user input.
I don't know how to ask it more clearly, but my goal is to define an integer array in Main(), then pass it to Interactive() where a user is supposed to enter 20 different ints and the program should add them to the array.
It would be tedious to continue defining new arguments for each object (like this):
int One = ArrayOne[0]
int Two = ArrayOne[1]
int Three = ArrayOne[2]
because I am filling 20 array objects, surely there is an easier way?
Can someone help?
Here is the code I am working with:
class Program
{
static void Main(string[] args)
{
int[] intArray = new int[20];
}
public static int[] Interactive(int[] args)
{
int[] ArrayOne = new int[20];
Write("\n Write an integer >>");
ArrayOne[0] = Convert.ToInt32(ReadLine());
foreach (int x in ArrayOne)
{
if (x != ArrayOne[0])
Write("\n Write another integer");
ArrayOne[x] = Convert.ToInt32(ReadLine());
WriteLine("\n {0}", ArrayOne[x]);
}
ReadLine();
return ArrayOne;
}
}

Try using a List. Unlike arrays their size can be dynamically changed.
using System.Collections.Generic;
public class Example
{
public static void Main()
{
List<int> numbers = new List<int>();
numbers.add(1);
numbers.add(2);
}
}

Are you looking for this?
int[] intArray = Interactive(values here);
public static int[] Interactive(int[] args)
{
//TODO:
}

Related

Deep copy a class with arrays [duplicate]

This question already has answers here:
C# Copy Array by Value
(8 answers)
Copy one 2D array to another 2D array
(4 answers)
Closed 2 years ago.
This is an addendum to a previous question I asked about copying classes.
The basic answer to the previous question (copying classes not as reference type) was to use a memberwise clone method to avoid keeping links between the two classes.
Doing this on a class with only int values works, but this breaks apart as soon as I introduce arrays in the mix. See the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyClass
{
public int[] myNumber;
public MyClass ShallowCopy()
{
return (MyClass)this.MemberwiseClone();
}
}
public class Test : MonoBehaviour
{
Dictionary<string, MyClass> myDictionary1 = new Dictionary<string, MyClass>();
Dictionary<string, MyClass> myDictionary2 = new Dictionary<string, MyClass>();
void Start()
{
myDictionary1.Add("a", new MyClass() { myNumber = new int[] { 1, 1 } });
myDictionary1.Add("b", new MyClass() { myNumber = new int[] { 2, 2 } });
myDictionary2["b"] = myDictionary1["a"].ShallowCopy();
myDictionary2["b"].myNumber[0] = 3;
Debug.Log(myDictionary1["a"].myNumber[0]); //output 3, I'd want it to still be 1
}
}
I've tried implementing the ShallowCopy method (implemented in line 9 and used in line 25) and it doesn't work. I should implement a DeepCopy method, but I don't know how to formulate it applied to arrays.
My new DeepCopy function would be something like
public MyClass DeepCopy()
{
MyClass other = (MyClass)this.MemberwiseClone();
other.myNumber = ?????????????????????? //int[] deep copy
return other;
}
But I have no idea how to formulate a copy of the array. I've found a similar thread dealing with this, but I couldn't adapt the solution to my case.
Thanks in advance!
If you know that your array is going to be full of value types like int, or you have reference types and you want both arrays to refer to the same instance, you can use CopyTo
int[] copyTarget = new int[copyFrom.length];
copyFrom.CopyTo(copyTarget, 0);
If your array can/does have reference types in it, and you don't want the new array to reference the same instances, you will have to instead move through the elements doing a memberwise clone of each:
int[] copyTarget = new int[copyFrom.length];
for(int i = 0; i < copyTarget.Length; i++)
{
copyTarget[i] = copyFrom[i].MemberwiseClone();
}

Declare an array of queues [duplicate]

This question already has answers here:
All possible array initialization syntaxes
(19 answers)
Closed 5 years ago.
What is the language grammatical problem in my code?
I want to declare an array of queues. Is this the right way to declare and use them?
public static void Main(string[] args)
{
Queue<int>[] downBoolArray = new Queue<int>[8]();
downBoolArray[0].Enqueue(1);
}
Your first problem is a syntax error: new Queue<int>[8]() should be new Queue<int>[8].
Once declared with the correct syntax, when you attempt to use an element of the array (downBoolArray[0].Enqueue(1)) you will encounter a NullReferenceException because array elements initialise to their default values which in the case of a reference type is null.
You could instead initialise your array with non-null seed values using a single line of LINQ:
Queue<int>[] downBoolArray = Enumerable.Range(1,8).Select(i => new Queue<int>()).ToArray();
The arguments to Range specify that we need 8 'entries' in our sequence; the Select statement creates a new Queue<int> for each item; and the ToArray call outputs our sequence as an array.
You need to initialize each element in your array
void Main()
{
Queue<int>[] downBoolArray =new Queue<int>[10];
for (int i = 0; i < downBoolArray.Length; i++)
downBoolArray[i] = new Queue<int>();
downBoolArray[0].Enqueue(1);
}
You've created an array of null values.
What you want is something like this:
public static void Main(string[] args) {
var queues = new Queue<int>[8];
// Possibly some other stuff
// Initialise all values
for (var i = 0; i < queues.Length; i++) {
// Accounting for maybe already sporadically initialising values
queues[i] = (queues[i]) ?? new Queue<int>();
}
// Do whatever
}

Creating objects from constructors with 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 5 years ago.
Improve this question
I'm a newbie and I'm trying to Console.Write() arrays from a constructor in Main. I am also trying to override ToString() to Console.Write() an array of ints as a string, but haven't found a clue how to do it.
namespace Z1
{
class List
{
public List(int b)
{
int[] tabb = new int[b];
Random r1 = new Random();
for(int i=0;i<b;i++)
{
tabb [i] =r1.Next(0, 100);
}
}
public List()
{
Random r2 = new Random();
int rInt1=r2.Next(0,10);
int[] tabc = new int[rInt1];
Random r3 = new Random();
for(int i=0;i<rInt1;i++){
tabc [i] = r3.Next(0,100);
}
}
}
class Program
{
static void Main()
{
List l1 = new List(10);
List l2 = new List();
Console.WriteLine(l1.ToString());
Console.WriteLine(l2.ToString());
}
}
}
The first thing to change are the two arrays. They are local variables and when you exit from the constructor they are simply discarded and you cannot use them anymore. I think you want just one array that could be created with a size specified by your user or with a random size between 1 and 10.
Finally you can override of ToString() in the usual way and return a Join of the array
class List
{
static Random r1 = new Random();
private int[] tabb;
public List(int b)
{
tabb = new int[b];
for (int i = 0; i < b; i++)
tabb[i] = r1.Next(0, 100);
}
// This constructor calls the first one with a random number between 1 and 10
public List(): this(r1.Next(1,11))
{ }
public override string ToString()
{
return string.Join(",", tabb);
}
}
Now your Main method could get the expected result.
As a side note, I suppose that this is just a test program so there is not much concern, but in a real program I strongly suggest you to avoid creating class with names that clashes with the classes defined in the framework. It is better to avoid names likes List, Task, Queue etc...
You can't just print the array, you'll have to print each value separately. Try using this instead of just Console.WriteLine();. Also make sure at the top of your class you have using LINQ;
l1.ToList().ForEach(Console.WriteLine);
l2.ToList().ForEach(Console.WriteLine);

Is there any way to initialize several variables from one array? [duplicate]

This question already has answers here:
c# multi assignment
(7 answers)
Closed 8 years ago.
In some languages it is possible to initialize several variables at the same time from an array.
For example in PHP you can do something like this:
$array = array('a', 'b', 'c');
list($a, $b, $c) = $array;
Is it possible to do this in C# as well?
I want to apply this on a program where I read all lines from a file where I know every line is two words only (never more, never less).
I know I can create the function myself (and sending in variables by reference with outkeyword) but I would like to know if any built in functionality exists for it.
I would like to know this mostly for the reason that if it is possible the code might be more readable for other developers.
In C#,
string[] arr1 = new string[] { "one", "two", "three" };
string s1 = arr1[0];
string s2 = arr1[1];
string s3 = arr1[2];
If readability is the issue and if I understand you correctly - I don't know of an in-built way. But you can create a function for that.
void Doit(out string one, out string two, string[] input)
{
one = input[0];
two = input[1];
}
And use it thus:
string[] s = new string[] { "First", "Second" };
string a, b;
Doit(out a, out b, s);
I just realized that you don't need my answer. (I had initially understood "I know I can create the function myself..." differently.) Perhaps, though, it can help someone else.
char[] array = new char[] {'a','b','c'};
As far as I know there is no buit-in way to do that.
Maybe a good way to implement that functionality is by using extension methods in order to improve readability.
Simply write the needed code in a extension method that can be attached to the type you want to initialize like a list in your example above and take an array as input to that function:
public static class Extensions {
public static void initFromArray<T> (this List<T> list, T[] array) {
for (int i = 0; i < array.Length; i++) {
list[i] = array[i];
}
}
}
Then you can use this method for example like in the following:
int[] array = new int [] { 1, 4, 6, 2, 5 };
List<int> list = new List<int>();
for (int i = 0; i < 4; i++) list.Add(0);
list.initFromArray<T>(array);

Fill List<int> with default values? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Auto-Initializing C# Lists
I have a list of integers that has a certain capacity that I would like to automatically fill when declared.
List<int> x = new List<int>(10);
Is there an easier way to fill this list with 10 ints that have the default value for an int rather than looping through and adding the items?
Well, you can ask LINQ to do the looping for you:
List<int> x = Enumerable.Repeat(value, count).ToList();
It's unclear whether by "default value" you mean 0 or a custom default value.
You can make this slightly more efficient (in execution time; it's worse in memory) by creating an array:
List<int> x = new List<int>(new int[count]);
That will do a block copy from the array into the list, which will probably be more efficient than the looping required by ToList.
int defaultValue = 0;
return Enumerable.Repeat(defaultValue, 10).ToList();
if you have a fixed length list and you want all the elements to have the default value, then maybe you should just use an array:
int[] x = new int[10];
Alternatively this may be a good place for a custom extension method:
public static void Fill<T>(this ICollection<T> lst, int num)
{
Fill(lst, default(T), num);
}
public static void Fill<T>(this ICollection<T> lst, T val, int num)
{
lst.Clear();
for(int i = 0; i < num; i++)
lst.Add(val);
}
and then you can even add a special overload for the List class to fill up to the capacity:
public static void Fill<T>(this List<T> lst, T val)
{
Fill(lst, val, lst.Capacity);
}
public static void Fill<T>(this List<T> lst)
{
Fill(lst, default(T), lst.Capacity);
}
Then you can just say:
List<int> x = new List(10).Fill();
Yes
int[] arr = new int[10];
List<int> list = new List<int>(arr);
var count = 10;
var list = new List<int>(new int[count]);
ADD
Here is generic method to get the list with default values:
public static List<T> GetListFilledWithDefaulValues<T>(int count)
{
if (count < 0)
throw new ArgumentException("Count of elements cannot be less than zero", "count");
return new List<T>(new T[count]);
}

Categories