如何从数据表中获取特定的列值?
问题描述:
我有一个数据表。我需要根据用户输入获取特定的列值。例如,假设数据表具有两列CountryID和CountryName。
I have a datatable. I need to fetch a certain column value based on the user input. For example, lets say the datatable has two columns CountryID and CountryName.
我需要根据用户输入的国家/地区名称在数据表中找到CountryID。我可以打开与数据库的连接,然后从CountryName = @userinput所在的国家/地区运行查询select countryID。无论如何,我可以在数据表上执行此操作。
I need to find CountryID in the datatable based on the user input country name. I could just open a connection with DB and run the query select countryID from Country where countryName = @userinput. Is there anyway i could do this on the datatable.
答
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();