Why is this considered going from string[] to int[]? - c#

It keeps giving me an error message here and I don't understand why.
int[] user31 = new int[53];
user31 = System.IO.File.ReadLines("ratings.txt").Skip(1675).Take(53).ToArray();

Because ReadLines returns strings, you know. It is right there in the documentation:
http://msdn.microsoft.com/en-us/library/dd383503(v=vs.110).aspx
and you just do "TOArray".
If you would parse the rows before doing ToArray....
Skip(1675).Take53.Select (x=> Int.Parse(x)).ToArray()
(or along this line)
You would get an array of ints, but calling ToArray on an enum of string returns an array of strings.

Just look at the return type of System.IO.File.ReadLines methods. It is String[].
You call Skip and Take as a result you will have an IEnumerable<String> calling ToArray again will give you a String[] not int[].

Because each line of a text file is just that, text. If you can guarantee that each line is actually an integer, you can do something like this:
int[] user31 = new int[53];
string[] lines = System.IO.File.ReadLines("ratings.txt").Skip(1675).Take(53).ToArray();
int i = 0;
foreach (var line in lines)
{
user31[i++] = Convert.ToInt32(lines[i]);
}

ReadLines returns strings with an array
I assume that your ratings.txt file contain int values in each line
you need to convert string array to int array ..
int[] user31 = new int[53];
user31= System.IO.File.ReadLines("ratings.txt").Skip(1675).Take(53).ToArray().Select(n => Convert.ToInt32(n)).ToArray();

This is because the user31 is an integer array but ReadLine returns string[].
Try like this:
List<string> str =new List<string>(new string[] {"123", "234","345","456","678","678","890"});
List<int> a = str.Skip(1675).Take(53).ConvertAll(new Converter<string, int>(int.Parse));
No need to explicitly parse it yourself and return an array. ConvertAllwill do the job to return an array.
EDIT:
Included a running test case using ConvertAll function.

Related

How to convert char[] to char?

I am new to C#. I am trying to declare a char array that contains few string values. Trying to use the ToCharArray() method to copy the string to a char array it return character array of a string. However, I get the error saying it cannot implicitly convert char[] to char.
Here's the code I have written:
char[] country= new char[5];
country[1] = "japan".ToCharArray();
country[2] = "korea".ToCharArray();
It works when I write it like this:
char[] country= "japan".ToCharArray();
but I want to use it in an array so I can randomize and choose an element from any of 5 values assigned. I would really appreciate if anyone could help, thanks.
I believe you try to have array of char arrays:
char[][] countries = new char[5][];
countries[1] = "japan".ToCharArray();
countries[2] = "korea".ToCharArray();
Every element in the array is one character.
So country[0] is "j", country[1] is "a" and so on.
with
country[1] = "japan".ToCharArray();
you try to put an array into a char, and give you an error.
Perhaps you want a list of chars. So you can use an array of array or a list of country.
for the first country for example
List<string> country = new List<string>() {
"japan",
"korea"
};
var random = new Random();
var character = country[0][random.Next(0, country[0].Length)];

FormatException on String to Int.ToList Conversion

string aresultlist = File.ReadAllLines(data).ToString();
var bresultlist = aresultlist.Split().Select(s => Convert.ToInt32(s));
List<int> resultlist = bresultlist.ToList();
Can anyone help with the FormatException I keep getting on this block, "It's the datetime Format, take date first exception". It's a string read from a space delimited text file.
Try this:
List<int> resultList = File
.ReadLines(data) // you've got IEnumerable<string>
.Select(line => line.Split()) // -/- IEnumerable<string[]>
.Select(ietms => int.Parse(items[0])) // -/- IEnumerable<int>
.ToList(); // finally, it's List<int>
I've assumed that it's the 1st item of the line which should be converted into int: int.Parse(items[0]), change 0 into the right index if required.
Try avoiding ReadAllLines in favor to ReadLines: you don't what all the file (which can be long) to be read into an array in one go
the problem is that ReadAllLines returns a string[]. If you call ToString on such an object you get the namespace.classname as a string. So in your case:
System.String[]
splitting this string results definetely not a number. But in a string[] with on entry, namely:
System.String[]
If your file has only one line with the space delimited numbers, I would suggest to use File.ReadAllText. It will read the entire content of the file and return it as 1 string. This way you can use your code almost as it is.
string aresultlist = File.ReadAllText(data);
var bresultlist = aresultlist.Split().Select(s => Convert.ToInt32(s));
List<int> resultlist = bresultlist.ToList();
EDIT:
As suggested by Gilad Green you might have content in the file that cannot be parsed to a number and will throw an exception. To avoid this you can follow this example

How to store text from a file-list into a variable in c#

Hi I am new to programming. I would like to read a text file and take the values ( strings ) and store each character of the string in an array individually. I have used a list to take in the vales from the text file. I am finding it difficult to move them into an array and then use those values in my program. Please find me a solution if possible. Thanking you in advance.
public class file_IO
{
string[] letters = new string[] //I would like to store it in this variable
public void File_Reader()
{
string filepath = #"env.txt"; //Variable to hold string
List<string> file_lines = File.ReadAllLines(filepath).ToList();//returns array of strings into List
foreach (string line in file_lines)
{
}
}
}
Hope this will work for you!.
public char[] File_Reader()
{
string filepath = #"env.txt"; //Variable to hold string
StreamReader sr = new StreamReader(filepath);
string fileContentInString = sr.ReadToEnd();
sr.Close();
return fileContentInString.ToCharArray();
}
List<List<char>> linesAsChars = File.ReadAllLines(filepath)
.Select(l => l.ToList())
.ToList();
This will get a List of List of chars.
string implements IEnumerable<char>, so with ToList each line in the file is translated to List<char>.
Solution to "store each character of the string in an array individually" is fairly easy because string is in fact an array of char. You can do this using something like this :
char[] letters;
public void File_Reader()
{
string filepath = #"env.txt";
letters = File.ReadAllText(filePath).ToArray();
}
I'm not really sure if I have understood your question properly, but from what I have read, I will assume that you want an array of lines (which are strings).
In this case, you don't need to do much as the File.ReadAllLines() method naturally outputs an array of string variables.
Remove the for loop and replace
List<string> file_lines = File.ReadAllLines(filepath).ToList();//returns array of strings into List
with:
letters = File.ReadAllLines(filepath)
In case what you want is actually an array of every char value in your file, I would refer to #m.rogalski's answer and declare an array of char[], for example, declare:
char[] fileChars;
and then replace the line I mentioned earlier with:
fileChars = readAllText(filePath).toCharArray()
You will notice that you do not need a loop in either of the above situations. Hope I helped.

Length of array created by using split string

I know that we can use string.split() to put our data into arrays like below:
string[] strSplit = Data.Split('|');
But can we know how many array items it created? I need that number.
It will create a single array of multiple strings. Like T.S. commented, you can get the number of strings using the length property of the returned array
int length = strSplit.length
Sometime you need remove the empty entries in spilt result:
string[] strSplit = data.Split(new []{"|"}, StringSplitOptions.RemoveEmptyEntries);
And get the length like this:
int length = strSplit.Length;

InvalidCastException trying to cast Object[] array to string array

I have a method that takes an ArrayList object as a parameter.
I then try to convert this arrayList into a string array but get an InvalidCastException.
The ArrayList contains a seven random numbers. As they are of the type object I am assuming it shouldnt be a problem casting it into a string.
This is the method that I have called
p.matches(winningNumber);
public void matches(ArrayList al)
{
try
{
string nameFile;
string[] winningNumber = (string[])al.ToArray(typeof(string));
Console.WriteLine("Please enter the name of the file you want to Read from");
nameFile = Console.ReadLine();
it is with the attemt at casting that I get an exception.
You are getting this exception because in order to convert to array of strings, the elements themselves must be strings as well. You can do it with LINQ, though:
string[] winningNumber = al.Cast<object>().Select(o => o.ToString()).ToArray();
To deal with nulls, replace o.ToString() with ""+o or a conditional that checks for nulls.
You just need to use Enumerable.Cast before you call ToArray
string[] winningNumber = al.Cast<string>().ToArray();
Change
string[] winningNumber = (string[])al.ToArray(typeof(string));
To
string[] winningNumber = al.Cast<object>.Select(x=> x==null ? string.Empty : x.ToString()).ToArray();
If you have some items that are not string, you can use Enumerable.OfType. It will ignore non string types.
string[] winningNumber = al.OfType<string>().ToArray();
string[] winningNumber = al.Cast<object>.Select(x=>Convert.ToString(x)).ToArray();

Categories