How to Get a Specific Column Value from a DataTable?
As per the title of the post I just needed to get all values from a specific column. Here is the code I used to achieve that.
public static IEnumerable<T> ColumnValues<T>(this DataColumn self)
{
return self.Table.Select().Select(dr => (T)Convert.ChangeType(dr[self], typeof(T)));
}
I suggest such way based on extension methods:
IEnumerable<Int32> countryIDs =
dataTable
.AsEnumerable()
.Where(row => row.Field<String>("CountryName") == countryName)
.Select(row => row.Field<Int32>("CountryID"));
System.Data.DataSetExtensions.dll needs to be referenced.
foreach (DataRow row in Datatable.Rows)
{
if (row["CountryName"].ToString() == userInput)
{
return row["CountryID"];
}
}
While this may not compile directly you should get the idea, also I'm sure it would be vastly superior to do the query through SQL as a huge datatable will take a long time to run through all the rows.
string countryName = "USA";
DataTable dt = new DataTable();
int id = (from DataRow dr in dt.Rows
where (string)dr["CountryName"] == countryName
select (int)dr["id"]).FirstOrDefault();