Getting a cell from DataTable.Row.ItemArray with Linq
11,297
Solution 1
You can also use the column-name to get the field value:
int item1 = row.Field<int>("Item1");
- DataRow.Item Property(String)
-
DataRow.Field Method:
Provides strongly-typed access
You could also use LINQ-to-DataSet
:
int[] allItems = (from row in dt.AsEnumerable()
select row.Field<int>("Item1")).ToArray();
or in method syntax:
int[] allItems = dt.AsEnumerable().Select(r => r.Field<int>("Item1")).ToArray();
Solution 2
If you use the Item indexer rather than ItemArray
, you can access items by column name, regardless of whether you use LINQ or not.
dt.Rows[0]["Column Name"]
Solution 3
Tim Schmelter's answer is probably what you are lookin for, just to add also this way using Convert
class instead of DataRow.Field
:
var q = (from row in dataTable.AsEnumerable() select Convert.ToInt16(row["COLUMN1"])).ToArray();
Comments
-
David Rasuli almost 2 years
I have the following ItemArray:
dt.Rows[0].ItemArray.. //{0,1,2,3,4,5}
the headers are : item0,item1,item2 etc..
So far, to get a value from the ItemArray I used to call it by an index.
Is there any way to get the value within the ItemArray with a Linq expression based on the column name?
Thanks
-
David Rasuli about 12 yearsHi Tim, thanks for your comment. I don't fully understand the syntax here as I wished to perform this action on a specific row (lets say Rows[0]) how do I see it at your example?
-
Tim Schmelter about 12 years@DavidRasuli: If you only have one row and you only want to get a specific field value, use the first method i've shown(
row.Field<int>("Item1")
). Otherwise explain what you're trying to achieve. -
David Rasuli about 12 yearsThanks, thats what I looked for .