Reputation: 239
I have a question regarding DataRows
. I have a DataTable
which I then converted into a list of DataRow
's. Now I want the string information stored in each DataRow
. How can I do this? This is my code:
List<DataRow> list = dt.AsEnumerable().ToList();
Upvotes: 16
Views: 115449
Reputation: 3744
In case you don't want to parse to a List first then loop through a List, you can loop through the columns in the DataTable by using a nested for
loop and accessing the .Columns.Count
property.
foreach (row in myDataTable.Rows){
for (int i = 0; i < myDataTable.Columns.Count; i++){
Console.WriteLine(row[i]);
}
}
Upvotes: 0
Reputation: 900
An alternative method in getting a list of DataRow
is to Select() the DataTable
. It returns a DataRow[]
that can easily be converted into a list.
Example of a 2 column DataTable
:
DataTable dt = new DataTable();
// TODO: Insert data into DataTable
foreach (DataRow row in dt.Select())
{
Console.WriteLine();
Console.WriteLine(row[0].ToString());
Console.WriteLine(row[1].ToString());
}
Upvotes: 1
Reputation: 1060
You will have to use a standard indexers on DataRow:
string someValue =
list[0]["SomeColumn"] as string;
Or, if you want to work with the array of data coming from a row,
ArrayList lst = new ArrayList(list[INDEX_OF_THE_ROW].Count);
foreach(object value in list[INDEX_OF_THE_ROW])
{
lst.Add(value);
}
Upvotes: 2
Reputation: 3801
List<DataRow> list = dt.AsEnumerable().ToList();
var mystring = list[0]["ColumnName"].ToString();
Upvotes: 1
Reputation: 189
This should do the trick.
string t = list[row]["column name"].ToString();
Upvotes: 2
Reputation: 21
You can retrieve it by column name or index. So if the string you are trying to retrieve is in first column you can do list[rowNum][0].ToString()
Upvotes: 0
Reputation: 7451
You could do this,
foreach(var row in list)
{
var value = row["ColumnName"] as string;
}
or this to get all string values of "ColumnName" lazily.
var values = list.Select(row => row["ColumnName"] as string);
Why would you turn a DataTable into a list, though? Just wondering.
Upvotes: 15
Reputation: 28228
Just use an index to access each element. The following code would acccess the first element in the list.
list[0].MyString;
Upvotes: 7