如何从DataTable获取特定列值?

时间:2010-05-26 20:35:31

标签: c# .net winforms

我有一个数据表。我需要根据用户输入获取某个列值。例如,假设数据表有两列CountryID和CountryName。

我需要根据用户输入的国家/地区名称在数据表中找到CountryID。我可以打开与DB的连接,并从countryName = @userinput的Country运行查询select countryID。无论如何,我可以在数据表上执行此操作。

6 个答案:

答案 0 :(得分:63)

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();

答案 1 :(得分:17)

foreach (DataRow row in Datatable.Rows) 
{
    if (row["CountryName"].ToString() == userInput) 
    {
        return row["CountryID"];
    }
}

虽然这可能无法直接编译,但您应该明白这一点,我也相信通过SQL进行查询将会非常优越,因为巨大的数据表需要很长时间才能遍历所有行。

答案 2 :(得分:9)

我建议这种方式基于扩展方法:

IEnumerable<Int32> countryIDs =
    dataTable
    .AsEnumerable()
    .Where(row => row.Field<String>("CountryName") == countryName)
    .Select(row => row.Field<Int32>("CountryID"));

需要引用System.Data.DataSetExtensions.dll。

答案 3 :(得分:1)

我想你可以使用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");
}

答案 4 :(得分:1)

数据表有一个.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

当然,如果userinput包含'character,则会引发异常(就像查询数据库一样)。你应该逃避'字符(我使用一个函数来做)。

答案 5 :(得分:0)

按照帖子的标题,我只需要从特定列获取所有值。这是我用来实现该目标的代码。

    public static IEnumerable<T> ColumnValues<T>(this DataColumn self)
    {
        return self.Table.Select().Select(dr => (T)Convert.ChangeType(dr[self], typeof(T)));
    }