In for each loop i am adding the contents into ArrayList. Now i need to add (or copy/move) the contents of arraylist into string array.
By string array i mean string[].
let me know if more info required.
thanks!
Use ToArray:
string[] array = (string[])list.ToArray(typeof(string));
I would recommend you use List<string> though, as that's more type safe:
List<string> list = ...
string[] array = list.ToArray();
Use the toArray() method:
ArrayList alist = ...;
String []strArray = new String[alist.size()];
alist.toArray(strArray);
You can use ToArray, which others have posted, but if you want to do some checking on the original list, or modify specific items as they're entered, you can also use something like this:
var myStringArray = new string[ArrayList.Count];
int i = 0;
foreach(var item in ArrayList)
{
myStringArray[i] = item;
i++;
}
Related
I've been trying to figure out how to remove elements in my ArrayList where the value contains some text string.
My Array could look like this:
[0] "\"MAERSKA.CO\",N/A,N/A,N/A,N/A,N/A,N/A"
[1] "\"GEN.COABB.ST\",N/A,N/A,N/A,N/A,N/A,N/A"
[2] "\"ARCM.ST\",\"Arcam AB\",330.00,330.50,332.00,330.50,330.00"
And my ArrayList is created like this:
string stringToRemove = "NA";
ArrayList rows = new ArrayList(csvData.Replace("\r", "").Split('\n'));
So the question is how I delete all entries that contains "NA".
I have tried the RemoveAt or RemoveAll with several combinations of Contains but i cant seem to get the code right.
I do not want to make a new Array if it can be avoided.
Regards
Flemming
If you want to reduce your ArrayList before instantiate your variable, consider using LINQ:
ArrayList rows = new ArrayList(csvData.Replace("\r", "").Split('\n').Where(r => !r.Contains(stringToRemove)).ToList());
If you want to reduce your ArrayList after instantiation, you can try this:
for (int i = 0; i < rows.Count; i++)
{
var row = (string)rows[i];
if (row.Contains(stringToRemove))
{
rows.RemoveAt(i);
i--;
}
}
The following code creates a list as output containing all strings except "N/A":
var outputs = new List<string>();
foreach (var item in input)
{
var splitted = item.Split(',');
foreach (var splt in splitted)
{
if (splt != "N/A")
{
outputs.Add(splt);
}
}
}
The input is your array.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Convert ArrayList into string array(string[]) in c#
How can I convert array list to string[]?below is code I am trying. I am getting an error:
At least one element in the source array could not be cast down to the destination array type.
ArrayList myArrayList = new ArrayList();
foreach (DataRow dtRow in DtSet.Tables[0].Rows)
{
myArrayList.Add(dtRow);
}
string[] myStringArray = (string[])myArrayList.ToArray(typeof(string));
Are you still using .NET 1.1. or why don't you use typed List<T> instead of an ArrayList?
First, you cannot cast a DataRow to String. You can cast every field of a DataRow to a string.
If you can use Linq you can use following code to get a String[] of all row fields where each field is separated by comma:
String[] rowFields = DtSet.Tables[0]
.AsEnumerable()
.Select(r => string.Join(",", r.ItemArray));
.ToArray();
You cannot take a DataRow (type) and add it to an ArrayList expecting it to be a string.
A DataRow is an object that has a myriad of information about the object as well as the objects data.
foreach(DataRow dtRow in dtSet.Tables[0].Rows)
{
myArrayList.Add(dtRow["UserName"].ToString());
}
string[] myArray = myArrayList.ToArray(typeof(string));
You are placing a number of DataRow objects into an ArrayList. DataRows are not strings. So: that can't work. At best, you can perhaps get the .ToString(), but frankly, that isn't going to be all that helpful - because every row will just say System.Data.DataRow (since it doesn't override ToString(). I think you need to re-evaluate what you are trying to do.
Example based on comment discussion:
DataTable table = ...
string[] strings = new string[table.Rows.Count];
int idx = 0;
foreach(DataRow row in table.Rows)
{
StringBuilder sb = new StringBuilder();
object[] cells = row.ItemArray;
for(int i = 0 ; i < cells.Length ; i++)
{
if (i != 0) sb.Append(',');
sb.Append('"').Append(cells[i]).Append('"');
}
strings[idx++] = sb.ToString();
}
You have an ArrayList whose elements are of type DataRow. You are trying to convert it into an array of strings. A DataRow is not a string (nor does it become one on downcasting), so you can't do that.
If the array of strings is what you ultimately want, you should probably call ToString (or whatever conversion you need) on each element while filling the ArrayList.
(Also, as Tim Schmelter said in comments, you should really be using a List<T> for some T -- probably either string or DataRow, depending on exactly how your code ends up looking -- rather than an ArrayList.)
Each item the arrayList is of type DataRow, you can't cast it to a string.
Instead, you should construct a string that represents the contents of the row, and add that string to the list, e.g.
myArrayList.Add(dtRow["CustomerName"]);
Have you tried this:
string[] array = myArrayList.ToArray(typeof(string)) as string[];
ArrayList myArrayList = new ArrayList();
myArrayList.Add("as");
myArrayList.Add("as");
myArrayList.Add("as");
myArrayList.Add("as");
myArrayList.Add("as");
myArrayList.Add("as");
string[] array = myArrayList.ToArray(typeof(string)) as string[];
foreach (var item in array)
{
Console.WriteLine(item.ToString());
}
Output:
as
as
as
as
as
as
I am reading some list of values in the result but I am not sure where I am going wrong, I wont know the array size so I cant assign any value to it
string[] result = null;
while (reader.Read())
{
result = Convert.ToString[](reader["RoleID"]);
}
reader.Close();
I am getting: Syntax error; value expected.
After I get the result value, how can I compare the values inside the result with a string? For example, I want to check whether the string check="Can send message"; is present in the result array or not. How can I do that?
Your code is syntactically wrong, hence the error. But when you have to build a collection of items but you do not know the size in advance, you want to use a List<T> as opposed to an array. The list will allow you to keep adding items.
var results = new List<string>();
while (reader.Read())
{
results.Add(reader["RoleID"].ToString());
}
// results now holds all of the RoleID values in the reader
You can access the elements of the list via index, just like an array, and can query the list using Linq (also just like an array) if needed.
string check = "something";
if (results.Any(item => item.Equals(check)))
{
// results contains the value in check
}
// or use all items that equal check
foreach (var item in results.Where(obj => obj.Equals(check))
{
// do something with each item that equals check
}
I preffer using ArrayList
var result= new ArrayList();
while (reader.Read())
{
result.Add(Convert.ToString[](reader["RoleID"]));
}reader.Close();
You should use a list as follows:
var results = new List<string>();
while( reader.Read() ){
results.Add(reader["RoleID"].ToString());
}
Then you would iterate through all the strings in the collection and check them using a foreach statement:
foreach(var result in results) {
if(result == "check") {
// do something
}
}
The list in Anthony Pegram's example can easily be converted to an array if needed.
string[] result = results.ToArray();
This is a very basic or rather simple question.
In my code, I'm using foreach value to put values in a string variable. For each iteration I want to store(add one after another) that variable value in an arraylist. Then retrieve arraylist values by its index.
Code I'm trying:
foreach(string abc in namestring)
{
string values = abc;
ArrayList list = new ArrayList();
list.Add(values);
}
For Example:
If 'namestring' contains values as tom, dik, harry. Then 'list' should
contain those values as list(0) = tom, list(1) = dik, list(2) =
harry.
Problem is with storing values in arraylist
You have to declare your ArrayList outside the loop:
ArrayList list = new ArrayList();
foreach(string abc in namestring)
{
list.Add(abc);
}
Also if you are on .NET 2.0 and above you should use the strongly typed List<string> instead:
List<string> list = new List<string>();
Declare ArrayList list = new ArrayList(); above the foreach
You might want to create your list before foreach loop. Atm you're creating foreach string in collection new list and then forgeting about its reference.
Looks like that your namestring is already a collection (implementing ICollection)... If so you can do it without a loop.
ArrayList list = new ArrayList();
list.AddRange(namestring);
return list;
or
List<string> list = new List<string>();
list.AddRange(namestring);
return list;
or, simple use the constructor
ArrayList list = new ArrayList(namestring);
or
List<string> list = new List<string>(namestring);
var list = new ArrayList();
foreach(string abc in namestring)
{
list.Add(abc);
}
Code can be fixed moving the "new ArrayList()" line outside of the foreach.
Anyway...
If 'namestring' contains values as tom, dik, harry. Then 'list' should
contain those values as list(0) = tom, list(1) = dik, list(2) = harry
namestring already contains those, as namestring[0] = tom, etc. so you could use it as it is.
I have a string array:
string[] names;
I want to remove all names that has length less than k. How can I do that? Do I have to convert it back to List<string> ?
Thanks,
Chan
Since a string[] can't change it size you can't remove elements from it. So you need to create a new, smaller array with names.Where(s=>!(s.Length<k)).ToArray().
On List<string> you can remove elements inplace with the RemoveAll(s=>s.Length<k) function.
Using LINQ would be like this
List<String> list1 = new List<string>();
List<String> list2 = list1.Except(list1.Where(c => c.Length < 10)).ToList();