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();
Related
I'm trying to convert a json string to a string array
my json string: "[\"false\",\"true\"]"
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
string[] strArray = new string[2];
strArray = js.Deserialize("[\"false\",\"true\"]", string[2]).ToArray();
but it only allows me to do a charArray.
I just need to be able to call my result as strArray[0] so that it will return "false"
Try doing:
strArray = js.Deserialize<string[]>("[\"false\",\"true\"]");
Your example code wouldn't compile. The second parameter should be a Type object, which string[2] isn't. It should be this:
strArray = js.Deserialize("[\"false\",\"true\"]", typeof(string[]));
Or, as the other answer mentioned, you can use the other, generic overload for the method:
strArray = js.Deserialize<string[]>("[\"false\",\"true\"]");
Either one will do exactly the same thing. It's just handy to be able to pass a Type object sometimes if you don't know beforehand what the actual type will be. In this case you do, so it doesn't matter.
Why not use Newtonsoft's JArray type? It is built for this conversion and can handle many edge cases automatically.
var jArray = JArray.Parse("[\"false\",\"true\"]");
var strArray = jArray.ToObject<string[]>()
This will give you a string array. But you could also elect to use .ToArray() to convert to a JToken array which can sometimes be more useful.
I've defined List
private class Kamery
{
public int iIndeks;
public string strNazwa;
public Kamery(int Indeks, string Nazwa)
{
iIndeks = Indeks;
strNazwa = Nazwa;
}
}
List<Kamery> lKamery = new List<Kamery>();
I'd like to cast searched list of names to string array like:
string[] strNazwa = (string)lKamery.Find(item => item.iIndeks == iIndeks).strNazwa.ToArray();
But compiler says Cannot convert type 'char[]' to 'string'
Why? How it needs to be done?
I think you want:
string[] strNazwa = lKamery.Where(item => item.iIndeks == iIndeks)
.Select(item => item.strNazwa)
.ToArray();
That will give you a string array that contains each of the strNazwa values from the list for items that meet the Where condition.
Here's what your original code was doing:
string[] strNazwa = (string)
// get the one item that matches the condition
lKamery.Find(item => item.iIndeks ==Indeks)
// get the strNazwa property from that one item
.strNazwa
// return the string as a char array
.ToArray();
When you try to cast the char[] to a string it fails since you can't cast it. You can create a string from a character array but not via a cast.
I think your problem is that .Find returns only 1 value , the first match in the list.
https://msdn.microsoft.com/en-us/library/x0b5b5bc(v=vs.110).aspx
This value will be a string and by using .toArray , you are converting that string to a char[ ] and then trying to cast it back to string.
I'm not that good at c# , so the generic solution would be:
Declare the array, do a foreach and every time the id matches put the name into the array and inc the index. This limits it somewhat as you have to have a fixed size, would probably be better to use List instead.
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.
Just a very small question.
I have a array list named li, where after my conditions I have the contents as:
li[0]="s";
li[1]="a";
li[2]="h";
li[3]="i";
li[4]="4";
Now I wrote the code as:
foreach (string value in li)
{
tb_output.Text = li.ToString();
}
Here, I want that for each list item, the elements should be stored in a string, which I want to display it in a textbox. But i am unable to get "sahil" in tb_output.
Can you tell me where I am wrong. I am unable to take it. I am a beginner, so it is a kind of trouble to me.
If li is a char[], use tb_output.Text = new String(li)
If li is a List<char>, use tb_output.Text = new String(li.ToArray())
If li is a string[] or List<string>, use tb_output.Text = String.Concat(li)
Otherwise, if li contains chars, use tb_output.Text = new String(li.Cast<char>().ToArray())
Otherwise, if li contains string, use tb_output.Text = String.Concat(li.Cast<string>())
You should avoid using ArrayLists whenever possible. Either use List<char> or char[] array. I've used char because you're only holding chars but you can change this to string if you're going to use more than one character.
With a char array, you can simply do this
string myString = new string(li);
Alternatively, you can simply use the String.Concat method and pass in the List or Array.
tb_output.Text = String.Concat(myArrayOrList);
Update for clarification of comment
If you want to use a List<T>, you can do this.
List<char> li = new List<char>() { 's', 'a', 'h', 'i', 'l' };
tb_output.Text = String.Concat(li);
If you really must use an ArrayList here then you can simply convert that ArrayList to an array of chars and use the first method described above (new string(myCharArray))
try
{
tb_output.Text = new string((char[])myArrayList.ToArray(typeof(char)));
}
catch(InvalidCastException ex)
{
//handle any problems with the casting
}
I've added a try..catch block for the ArrayList because if there's an element in the array list that can't be cast to a char then an InvalidCastException is thrown. This isn't generally needed with a List<char> because you know that the list can only have chars in them whereas an ArrayList can have any object type.
Update 2 based on comments
The line new string((char[])myArrayList.ToArray(typeof(char)) can be broken down.
First we are converting the ArrayList to an Array using the the method ToArray()
myArrayList.ToArray();
However, we want to tell the ToArray method to convert every object inside to the ArrayList to a char because, at the moment, the ArrayList is holding object types and not char types. So we pass that information into the method.
myArrayList.ToArray(typeof(char));
We can create a new string from an array of chars by doing
string newString = new string(arrayOfChars);
At the moment we have an Array from the ToArray method but the string constructor here needs an array of chars (char[]) so we cast the Array that we have to a char[] which is why we have
(char[])myArrayList.ToArray(typeof(char));
So we now have a char[] from the original ArrayList and can pass that into the string constructor.
new string((char[])myArrayList.ToArray(typeof(char)));
You still haven't given a reason for why you're using an ArrayList but you'll have to deal with potential performance issues and casting exceptions as you may accidentally put an object into the ArrayList that can't be converted into a char (which is why we have the Try..Catch block).
How about trying
foreach (string value in li)
{
tb_output.Text += value;
}
The other answers should work for your particular question, however, if you want to write to that textbox the contents of li, you should instead do it in this manner.
string word = "";
foreach(string s in li)
{
word += s;
}
tb_output.Text = s;
That way, you clear out the textbox each time you write the array to it.
Better yet, especially if are dealing with a large array, improve performance by using StringBuilder (which you can get by adding "using System.Text;" to the top of your file.
StringBuilder stb = new StringBuilder();
foreach(string s in li)
{
stb.Append(s);
}
tb_output.Text = stb.ToString();
You need to append with +=
foreach (string value in li)
{
tb_output.Text += li.ToString();
}
You can join all elements from an array using String.Join method.
It takes two parameters, the first is: "join with what?", you can join the elements and separate them with a comma for example. The second parameter is your IEnumerable<T>, you can join elements of a List<T> and anything that comes from IEnumerable<T>.
So you could do
tb_output.Text = String.Join("", li);
This will return the string sahi4 as we are joining the array with an empty string.
Or you can use String.Concat already mentioned by keyboardP.
tb_output.Text = String.Concat(li);
Which will concatenate all values.
Alternatively you could build the string using a StringBuilder.
StringBuilder b = new StringBuilder();
foreach (string value in li)
{
sb.Append(value);
}
tb_output.Text = sb.ToString(); // returns the built string
Foreach will return one element at time from your li array and put into value as you named it. Instead of trying to use li.ToString() which will convert the array to a string inside the foreach, you should use value to get the string in each position...
Also, if you are concatenating strings you should use StringBuilder in cases like these, but you could also use the operator +.
stringA = stringA + "B"; // or
stringA += "B";
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
C# Textbox string separation
I want to pass the string value ie (red,blue,black) to a string array. I used the following code
string[] splitString = myString;
I am getting this error
Error 137 Argument '1': cannot convert from 'string' to 'char[]'
regards,
string[] splitString = myString.Split(",");
Try Split method of String class:
myString.Split(',');
To have a complete grip over various scenerios, you can visit .Net Perls
You should have a look at the String.Split method
string myString = "red,blue,black";
string[] splitString = myString.Split(',');
You are trying to assign a string directly to a string[] - this can't work. You need to do something with the string first - the String.Split method looks like a good fit:
string[] splitString = "red,blue,black".Split(',');
string myString = "red,blue,black";
string[] splitString = myString.Split(',');
foreach(string s in splitString)
Console.WriteLine(s);
Try it like below,
string myString = "red,blue,green";
string[] splitString = new string[1];
splitString[0] = myString;
or
string[] splitString = myString.Split(',');
string.Split()
Or just for an alternative:
string myString = "red,blue,black";
var strArr = Regex.Split(myString, ",");
If I read your question correctly you're not trying to split the string, you just need an array with one or more strings, right? In that case you'd do something like this:
string[] splitString = new string[]{ "red", "blue", "black" };
Your problem is that, you try to assign a type to array of type.
If you declare an array, then you need to initialize it with operator new.
String[] arrayOfString = new String[3];
In above piece of code you declare a variable arrayOfString that is an array of String object. This mean that in arrayOfString you can expect String.
After that you assign to it new array instance for three String objctes (new String[3]), in this step you only reserve memory for three elements.
After this you are able to store any String object in arrayOfString.
To store a object in array you just have to use the variable name and indexer.
arrayOfString[0] = "StackOverflow";
In this example we assign, an String into arryOfString under index 0.
In C# array are indexed from 0 to declared size - 1, that in this case is 2.