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
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.
I am trying to create a DataRow which gets some values from hard-coded strings or string variables, and the rest of the values from a collection's values, System.Collections.Generic.Dictionary<string, double>.ValueCollection to be specific. In my attempt below, I'm casting to an array but that doesn't work.
DataTable source = new DataTable();
foreach (string sample in GridSource.SampleName)
{
SampleDictionaries sd = GridSource.Data.Where(x => GridSource.Data.IndexOf(x) == GridSource.SampleName.IndexOf(sample)).First();
source.Rows.Add(sample, "Average", sd.Avg.Values.ToArray());
source.Rows.Add("", "Std. Deviation", sd.StdDev.Values.ToArray());
}
The code above produces this:
I understand what is happening here. My question is this: is there an easy way to tell the DataRow "Fill the remaining column values with this collection," or am I going to have to come up with some loop to do it?
what you can do is create the row from the datatable.NewRow() method. Then you can have the items array of the row equal an array of data:
DataTable source = new DataTable();
foreach (string sample in GridSource.SampleName)
{
DataRow temp = source.NewRow();
SampleDictionaries sd = GridSource.Data.Where(x => GridSource.Data.IndexOf(x) == GridSource.SampleName.IndexOf(sample)).First();
temp.ItemArray = new object[]{sample, "Average"}.Concat(sd.Avg.Values.ToArray());
source.Rows.Add(temp);
temp = source.NewRow();
temp.ItemArray = new object[]{"", "Std. Deviation".Concat(sd.StdDev.Values.ToArray());
}
Found an answer, with help from KMoussa!
source.Rows.Add(new object[] { "", "Std. Deviation"}.Concat(sd.StdDev.Values.Cast<object>().ToArray()).ToArray());
Very similar to what he recommended, but it was missing a second cast to array at the end.
I'm trying to transfer my datatable contents to another array. I am only going to get specific fields from the datatable, but I do not know how to save the specific columns content to another array.
What I did:
dr = SuperViewBLL.GetSomeStuff();
string[] new_array;
if (dr.Rows.Count > 0)
{
for (int i = 0; i < dr.Rows.Count;i++ )
{
new_array[i] = dr.Rows[i]['StuffLocationId'];
// I do know this is wrong
}
}
How can I get the column StuffLocationId to the array new_array?
That line is almost right, except that you need double quotes rather than single and you also need to cast/convert the value to type String to put it into a String array:
new_array[i] = (string) dr.Rows[i]["StuffLocationId"];
or, if the data is nullable:
new_array[i] = dr.Rows[i]["StuffLocationId"] as string;
The issue is that the array doesn't exist because you haven't created it. In order to create an array you have to know the size. If you haven't specified a size, either implicitly or explicitly, then you haven't created an array. This:
string[] new_array;
should be this:
string[] new_array = new string[dr.Rows.Count - 1];
You can also throw a bit of LINQ at the problem and succinctify the code a bit:
var new_array = dr.AsEnumerable()
.Select(row => row["StuffLocationId"] as string)
.ToArray();
That's also an example of specifying the size of the array implicitly.
This way is much more clear:
dt = SuperViewBLL.GetSomeStuff();
List<string> list = new List<string>();
foreach(DataRow row in dt.Rows)
{
list.Add((!row.IsNull("StuffLocationId") ? row["StuffLocationId"] as string : string.Empty));
}
Updated with the help of #jmcilhinney
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++;
}
Best practice when converting DataColumn values to an array of strings?
[Edit]
All values for certain DataColumn for all DataTable rows to be converted to an array of string?
If I understood your goal you want to specify a particular column and return all its values as a string array.
Try these approaches out:
int columnIndex = 2; // desired column index
// for loop approach
string[] results = new string[dt.Rows.Count];
for (int index = 0; index < dt.Rows.Count; index++)
{
results[index] = dt.Rows[index][columnIndex].ToString();
}
// LINQ
var result = dt.Rows.Cast<DataRow>()
.Select(row => row[columnIndex].ToString())
.ToArray();
You could replace columnIndex with columnName instead, for example:
string columnName = "OrderId";"
EDIT: you've asked for a string array specifically but in case you're flexible about the requirements I would prefer a List<string> to avoid the need to determine the array length prior to the for loop in the first example and simply add items to it. It's also a good opportunity to use a foreach loop instead.
I would then rewrite the code as follows:
List<string> list = new List<string>();
foreach (DataRow row in dt.Rows)
{
list.Add(row[columnIndex].ToString());
}
DataRow.ItemArray Property -
http://msdn.microsoft.com/en-us/library/system.data.datarow.itemarray.aspx
Also, which version are you using? You should check out the DataTableExtensions class -
http://msdn.microsoft.com/en-us/library/system.data.datatableextensions.aspx
And the DataRowExtensions class -
http://msdn.microsoft.com/en-us/library/system.data.datarowextensions.aspx
I know this question is old, but I found it in my Google search trying to do something similar. I wanted to create a list from all the values contained in a specific row of my datatable. In my code example below, I added a SQL datasource to my project in Visual Studio using the GUI wizards and I dropped the needed table adapter into the designer.
'Create a private DataTable
Private authTable As New qmgmtDataSet.AuthoritiesDataTable
'Fill the private table using the table adapter
Me.AuthoritiesTableAdapter1.Fill(Me.authTable)
'Make the list of values
Dim authNames As List(Of String) = New List(Of String)(From value As qmgmtDataSet.AuthoritiesRow In Me.authTable.Rows Select names.authName)