want to move each array from arrayList into int [ ] - c#

there are 350 elements in my arraylist , each of it consist of an array of 9 integers i-e Count of each element is 9 . i want to retrievere each of it.
here is what i am trying but giving me
error
"Unable to cast object of type
'System.Collections.Generic.List`1[System.Int32]' to type
'System.Int32[]'."
FileName = "E:\\Normalized_sheet1.txt";
FileStream Fs = File.OpenRead(FileName);
StreamReader SR = new StreamReader(Fs);
while (!SR.EndOfStream)
{
Line = SR.ReadLine().Split('\t'); //make an array of text each time
List<string> arr = new List<string>();
arr.AddRange(Line);
List<int> intList = arr.ConvertAll(s => Int32.Parse(s));
myvalues.Add(intList);
}
SR.Close();
Fs.Close();
for (i = 0; i < Samples; i++)
{
InputParameter=(int[]) myvalues[i]; // Error
}

myvalues.Add(intList.ToArray());
Because you mentioned that you have a list of arrays. If it's a List<int[]> then you can't add lists to it - you can only add arrays. ToArray() returns an array of the items in your list.

If "myvalues" is a List of int[] then your loop should look like this:
for (i = 0; i < Samples; i++)
{
InputParameter= myvalues[i]; //don't need cast.
}
if myvalues is a List of List of int, then your code should be:
for (i = 0; i < Samples; i++)
{
InputParameter= myvalues[i].ToArray();
}

Do not cast, use the appropriate List method:
InputParameter=myvalues[i].ToArray();

Related

How to implement string[] into string[] in C#?

I want to implement 'string[] loadedText' into 'string[] dataList', but I keep getting an error saying "Cannot implicitly convert type 'string[]' to 'string'".
string[] dataList = new string[1800];
StreamReader loadNewData = new StreamReader("podaciB.txt");
int i = 0;
while (i < 1800)
{
string[] loadedData = loadNewData.ReadLine().Split(';');
dataList[i] = loadedData;
i++;
}
I need the 'dataList' array that will contain 1800 'loadedData' arrays which contain 4 strings in them.
What you need is a jagged array:
string[][] dataList = new string[1800][];
loadNewData.ReadLine().Split(';'); returns array of string and you are storing array of strings into dataList[i] i.e. string element of string array. This is the reason behind error which you mentioned in your question
If you want to store loadNewData.ReadLine().Split(';'); into an array then I would suggest you to use nested list List<List<string>>
Something like,
List<List<string>> dataList = List<List<string>>();
StreamReader loadNewData = new StreamReader("podaciB.txt");
int i = 0;
while (i < 1800)
{
var innerList = loadNewData.ReadLine().Split(';').ToList();
dataList.Add(innerList);
i++;
}
It seems you need an array of array of strings, something like string[][].
You can do it like this:
string[][] dataList = new string[1800][];
StreamReader loadNewData = new StreamReader("podaciB.txt");
int i = 0;
while (i < 1800)
{
string[] loadedData = loadNewData.ReadLine().Split(';');
dataList[i] = loadedData;
i++;
}
As you are splitting loadedNewData, you receive string[] already, because Split() function returns string[].

Adding new items to string array

I am trying to add 2 new array items to existing string array. I achieved the result but I am sure this is not the right way to do .
How can I add items to a string array.
string[] sg = {"x", "y" };
string[] newSg = {"z", "w"};
string[] updatedSg = new string[sg.Length+newSg.Length];
for (int i = 0; i < sg.Length; i++)
{
updatedSg[i] = sg[i];
}
for (int i = 0; i < newSg.Length; i++)
{
updatedSg[sg.Length+i] = newSg[i];
}
You cannot add items to an array. You can use another container type, like a List, or you can create a new array with more elements and copy the old elements over. But you cannot add elements to an array and you cannot remove elements from an array. The number of elements in an array is fixed.
You can Concat two arrays into one by using Linq:
string[] updatedSg = sg
.Concat(newSg)
.ToArray();
An alternative is using List<String> for updatedSg collection type instead of array:
List<string> updatedSg = new List<string>(sg);
updatedSg.AddRange(newSg);
If you insist on updating an existing array then in general case you can have:
// imagine we don't know the actual size
string[] updatedSg = new string[0];
// add sg.Length items to the array
Array.Resize(ref updatedSg, sg.Length + updatedSg.Length);
// copy the items
for (int i = 0; i < sg.Length; ++i)
updatedSg[updatedSg.Length - sg.Length + i - 1] = sg[i];
// add updatedSg.Length items to the array
Array.Resize(ref updatedSg, newSg.Length + updatedSg.Length);
// copy the items
for (int i = 0; i < newSg.Length; ++i)
updatedSg[updatedSg.Length - newSg.Length + i - 1] = newSg[i];
If i have to add items to an array dynamically, i would use a List instead of an Array (Lists have an Add() method very useful). You could even convert it to an array at the end of the process (with ToArray() method). But you can also use methods like Concat() as mentioned above.
Using CopyTo()
var updatedSg = new string[sg.Length + newSg.Length];
sg.CopyTo(updatedSg, 0);
sgNew.CopyTo(updatedSg, sg.Length);
As answered here
https://stackoverflow.com/a/1547276/7070657
Or per somebody's suggestion:
var temp = x.Length;
Array.Resize(ref x, x.Length + y.Length);
y.CopyTo(x, temp); // x and y instead of sg and sgNew

Reading input from a text file, converting into int, and storing into array.

I need some help. I have a text file that looks like so:
21,M,S,1
22,F,M,2
19,F,S,3
65,F,M,4
66,M,M,4
What I need to do is put the first column into an array int[] age and the last column into an array int[] districts. This is for a college project due in a week. I've been having a lot of trouble trying to figure this out. Any help would be greatly appreciated. I did try searching for an answer already but didn't find anything that i understood. I also cannot use anything we havent learned from the book, so it rules out lists<> and things of the like.
FileStream census = new FileStream("census.txt", FileMode.Open, FileAccess.Read);
StreamReader inFile = new StreamReader(census);
string input = "";
string[] fields;
int[] districts = new int[SIZE];
int[] ageGroups = new int[SIZE];
input = inFile.ReadLine();
while (input != null)
{
fields = input.Split(',');
for (int i = 0; i < 1; i++)
{
int x = int.Parse(fields[i]);
districts[i] = x;
}
input = inFile.ReadLine();
}
Console.WriteLine(districts[0]);
if your file is nothing but this then File.ReadAllLines() will return a string array with each element being a line of your file. Having done that, you can then use the length of the returned array to initialize the other two arrays, into which the data will be stored.
Once you have your string array you call string.Split() on each element with "," as your delimiter, now you will have another array of strings minus the commas, you will them take the values you want by their index position, 0 and 3 respectively, and you can store those somewhere. Your code would look something like this:
//you will need to replace path with the actual path to the file.
string[] file = File.ReadAllLines("path");
int[] age = new int[file.Length];
int[] districts = new int[file.Length];
int counter = 0;
foreach (var item in file)
{
string[] values = item.Split(',');
age[counter] = Convert.ToInt32(values[0]);
districts[counter] = Convert.ToInt32(values[3]);
counter++
}
Proper way of writing this code:
Write each step your trying to perform:
// open file
// for each line
// parse line
Then refine "parse line"
// split by fields
// parse and handle age
// parse and handle gender
// parse and handle martial status
// parse and handle ....
Then start writing missing code.
At that point you should figure out that iterating through fields of single record not going to do you any good as all fields have different meaning.
So you'll need to remove for and replace it with filed-by-field parsing/assignments.
Instead of looping through all your fields, simply refer to the actual index of the field:
Wrong:
for (int i = 0; i < 1; i++)
{
int x = int.Parse(fields[i]);
districts[i] = x;
}
Right:
districts[i] = int.Parse(fields[0]);
ageGroups[i] = int.Parse(fields[3]);
i++;
So I just made some BS to do what you are seeking. I do not agree with it because I hate directly hardcoding for split, but since you can't use a list this is what you get:
FileStream census = new FileStream(path, FileMode.Open, FileAccess.Read);
StreamReader inFile = new StreamReader(census);
int[] districts = new int[1024];
int[] ageGroups = new int[1024];
int counter = 0;
string line;
while ((line = inFile.ReadLine()) != null)
{
string[] splitString = line.Split(',');
int.TryParse(splitString[0], out ageGroups[counter]);
int.TryParse(splitString[3], out districts[counter]);
counter++;
}
This will give you two arrays, districts and ageGroups that are of length 1024 and will contain the values for each row in the census.txt file.

Adding string list item to int array

Hello I need to take string item from string list and a add it to the int array i trying like this but its writing me error Cannot implicity convert type int to int[]
but in for sequence i adding only one int to one item in array so what is wrong please
private void buttonGenerateO_Click(object sender, EventArgs e)
{
List<string> AgentNumbers = new List<string>();
List<string> AgentRide = new List<string>();
int pocet = AgentNumbers.Count;
int[][] dvouRozmernePole = new int[2][];
dvouRozmernePole[0] = new int[pocet];
dvouRozmernePole[1] = new int[pocet];
foreach (string AgeNumb in AgentNumbers)
{
for (int i = 0; i < dvouRozmernePole[0].Length; i++)
dvouRozmernePole[i] = Convert.ToInt32(AgeNumb);
}
foreach (string AgeRide in AgentRide)
{
for (int i = 0; i < dvouRozmernePole[1].Length; i++)
dvouRozmernePole[i] = Convert.ToInt32(AgeRide);
}
Look at this declaration:
int[][] dvouRozmernePole = new int[2][];
So dvouRozmernePole is an array of arrays. Now look here:
dvouRozmernePole[i] = Convert.ToInt32(AgeNumb);
You're trying to assign an int value to dvouRozmernePole[i], which you can't do because it should be an int[].
I suspect you want:
dvouRozmernePole[0][i] = Convert.ToInt32(AgeNumb);
Having said that, given these lines:
List<string> AgentNumbers = new List<string>();
List<string> AgentRide = new List<string>();
int pocet = AgentNumbers.Count;
int[][] dvouRozmernePole = new int[2][];
dvouRozmernePole[0] = new int[pocet];
dvouRozmernePole[1] = new int[pocet];
... you'll always have empty lists anyway, so there are no values to convert.
Do you really need to use arrays at all? Using List<T> everywhere would almost certainly be simpler.
LINQ can also make this simpler. For example:
int[] numbers = AgentNumbers.Select(x => int.Parse(x)).ToArray();
int[] rides = AgentRide.Select(x => int.Parse(x)).ToArray();
int[][] dvouRozmernePole = { numbers, rides };
dvouRozmernePole is an array of int[], while Convert.ToInt32 returns an int. Therefore in:
dvouRozmernePole[i] = Convert.ToInt32(AgeNumb);
dvouRozmernePole[i] is an int[], and you are trying to assign an int.
It looks like you want:
dvouRozmernePole[0][i] = Convert.ToInt32(AgeNumb);
and later
dvouRozmernePole[1][i] = Convert.ToInt32(AgeRide);
You could instead do:
int[][] dvouRozmernePole = new int[2][]
{
AgentNumbers.Select(num => Convert.ToInt32(num)).ToArray(),
AgentRide.Select(ride => Convert.ToInt32(ride)).ToArray()
};
to initialise the array.
The error is quite clear. In the statement
dvouRozmernePole[i] = Convert.ToInt32(AgeNumb);
you assign an integer to an array.
dvouRozmernePole is an array of array of ints
so dvouRozmernePole[i] expects and int[] rather than the int value
try
did you mean
for (int i = 0; i < dvouRozmernePole[0].Length; i++)
dvouRozmernePole[0][i] = Convert.ToInt32(AgeNumb);
}
foreach (string AgeRide in AgentRide)
{
for (int i = 0; i < dvouRozmernePole[1].Length; i++)
dvouRozmernePole[1][i] = Convert.ToInt32(AgeRide);
}

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