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[].
Related
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;
}
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();
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.
I want to remove the element form the array. Actually I don't know the the index of the element and want to remove through it's value. I have tried a lot but fail. This is the function which i used to add element in the Array
string [] Arr;
int i = 0;
public void AddTOList(string ItemName)
{
Arr[i] = ItemName;
i++;
}
And I want to remove the element by the value. I know the below function is wrong but I want to explain what I want:
public void RemoveFromList(string ItemName)
{
A["Some_String"] = null;
}
Thanks
If you want to remove items by a string key then use a Dictionary
var d = new Dictionary<string, int>();
d.Add("Key1", 3);
int t = d["Key1"];
Or something like that.
Array has a fixed size, which is not suitable for your requirement. Instead you can use List<string>.
List<string> myList = new List<string>();
//add an item
myList.Add("hi");
//remove an item by its value
myList.Remove("hi");
List<string> list = new List<string>(A);
list.Remove(ItemName);
A = list.ToArray();
and #see Array.Resize
and #see Array.IndexOf
You can iterate through every value in array and if found then remove it. Something like this
string[] arr = new string[] { "apple", "ball", "cat", "dog", "elephant", "fan", "goat", "hat" };
string itemToRemove = "fan";
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == itemToRemove)
{
arr[i]=null;
break;
}
}
I got a table (in file) which I split into blocks by spaces.
I need structure like this:
-----------------------------
|21|22|23|33|3323|
|32|32|
|434433|545454|5454|
------------------------------
It's more like each row is its own table. How should I do this?
I tried List<List<string>> matrix = new List<List<string>>(); but I can't seem to find a way to work with it.
EDIT - can someone tell me what's wrong with this code???? Matrix[0][0] is same as matrix [1][0].. it seems that same row is added to matrix all the time, but I clear it ...
static ArrayList ReadFromFile(string filename)
StreamReader SR;
string S;
string[] S_split;
SR = File.OpenText(filename);
S = SR.ReadLine();
ArrayList myItems = new ArrayList();
List<List<string>> matrix = new List<List<string>>();
List<string> row = new List<string>();
while (S != null)
{
row.Clear();
S_split = S.Split(' ');
for (int i = 1; i < S_split.GetLength(0); i++)
{
row.Add(S_split[i]);
matrix.Add(row);
}
S = SR.ReadLine();
}
Console.WriteLine(matrix[1][1]);
SR.Close();
return myItems;
}
Not sure if I understand this correctly.
List<List<int>> table = new List<List<int>>();
List<int> row = new List<int>();
row.Add(21);
row.Add(22);
row.Add(23);
row.Add(33); // and so on
table.Add(row);
row = new List<int>();
row.Add(1001);
row.Add(1002);
table.Add(row);
MessageBox.Show(table[0][3].ToString());
The program should show a message box with text "33".
You should be able to work with it as you'd expect to deal with a list within a list.
matrix.Add(new List<string>);
matrix[0].Add("a string");
List<List<String>> matrix = new List<List<String>>();
foreach (String line in file)
{
String[] values = line.Split(new Char[] { ' ' });
matrix.Add(new List<String>(values));
}
Just iterate through your file and for every line do the following.
Generate a new List
Fill it with the data for the line
Add the list for the current line to your list for the complete file
Note that foreach (String line in file) is just pseudo code. Further you can merge the to lines in the body to a single line.
matrix.Add(new List<String>(line.Split(new Char[] { ' ' })));
You're describing a jagged array. I'm not exactly sure if a List won't be overkill? If you just have to import the data from the file and than use it, a jagged array should be simple enough.
Example:
int[][] jaggedArray = new int[][]
{
new int[] {21, 22, 23, 33, 3323},
new int[] {32, 32},
new int[] {434433, 545454, 5454}
};
you can also buildup the jagged array in a loop while processing your file, like this:
int[][] result = new int[numberOfLines][];
for (int currentLine = 0; currentLine < numberOfLines; currentLine++)
{
String line = fileStream.ReadLine();
int[] values = SplitAndConvertLine(line);
result[currentLine] = values;
}
If you are trying to read from the file then try something like the following (Note the following code has not been run through a compiler)
List<string[]> matrix = new List<string[]>();
while(!instream.EndOfStream)
{
var values = instream.ReadLine().Split(new[] {' '});
matrix.Add(values);
}