我有一个数据表。根据用户输入,我需要获取特定列的值。例如,假设数据表有两列CountryID和CountryName。
我需要根据用户输入的国家名称在数据表中查找对应的CountryID。我可以打开与数据库的连接并运行查询select countryID from Country where countryName = @userinput。但是否有方法可以在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();
foreach (DataRow row in Datatable.Rows)
{
if (row["CountryName"].ToString() == userInput)
{
return row["CountryID"];
}
}
虽然这段代码可能无法直接编译,但你应该已经理解了。同时,我相信通过 SQL 查询会更好,因为对于大量数据行来说,使用 DataTable 将需要很长时间才能运行完毕。我建议使用扩展方法的方式:
IEnumerable<Int32> countryIDs =
dataTable
.AsEnumerable()
.Where(row => row.Field<String>("CountryName") == countryName)
.Select(row => row.Field<Int32>("CountryID"));
需要引用System.Data.DataSetExtensions.dll。
Datatables有一个 .Select 方法,根据您指定的条件返回行数组。像这样:
Dim oRows() As DataRow
oRows = dtCountries.Select("CountryName = '" & userinput & "'")
If oRows.Count = 0 Then
' No rows found
Else
' At least one row found. Could be more than one
End If
当然,如果用户输入包含“字符”,它会引发异常(例如,如果您查询数据库)。您应该转义“字符”(我使用函数来执行此操作)。
根据帖子标题,我只需要从特定列中获取所有值。以下是我用来实现此目的的代码。
public static IEnumerable<T> ColumnValues<T>(this DataColumn self)
{
return self.Table.Select().Select(dr => (T)Convert.ChangeType(dr[self], typeof(T)));
}
我想你可以使用DataView对象,这样就可以利用RowFilter属性,具体请参考这里:
http://msdn.microsoft.com/en-us/library/system.data.dataview.rowfilter.aspx
private void MakeDataView()
{
DataView view = new DataView();
view.Table = DataSet1.Tables["Countries"];
view.RowFilter = "CountryName = 'France'";
view.RowStateFilter = DataViewRowState.ModifiedCurrent;
// Simple-bind to a TextBox control
Text1.DataBindings.Add("Text", view, "CountryID");
}
int weight = dataTable.Rows[0].Field<int>(0);
string code = dataTable.Rows[0].Field<string>(2);
// 通过列名获取第二个和第四个字段的值。
string name = dataTable.Rows[0].Field<string>("Name");
DateTime date = dataTable.Rows[0].Field<DateTime>("Date");