0

我的数据表中有五行(包含 AccountId、Name、Email、Address 列),我想根据 AccountId 获取特定行,因为所有五行都有不同的 AccountID。我想根据 AccountID 过滤它。我的意思是我只需要数据表中的一行来根据 AccountId 进行处理。

如何从包含我已传递的 AccountId 的数据表中获取特定行?

4

3 回答 3

1

三个选项:

  • 使用DataTable.Select, 提供过滤器表达式
  • 自己迭代行
  • 使用带有数据表扩展的 LINQ

我个人建议使用最后一个选项(LINQ):

var row = table.AsEnumerable()
               .FirstOrDefault(r => r.Field<string>("AccountID") == accountID);
if (row != null)
{
    // Use the row
}
于 2012-06-11T11:46:08.527 回答
0

您是否查看过 DataTable.Select() 方法?

http://msdn.microsoft.com/en-us/library/system.data.datatable.select(v=vs.100).aspx

public class DataTableExample 
{     
    public static void Main()     
    {         
        //adding up a new datatable         
        DataTable dtEmployee = new DataTable("Employee");            
        //adding up 3 columns to datatable         
        dtEmployee.Columns.Add("ID", typeof(int));         
        dtEmployee.Columns.Add("Name", typeof(string));         
        dtEmployee.Columns.Add("Salary", typeof(double));           
        //adding up rows to the datatable         
        dtEmployee.Rows.Add(52, "Human1", 21000);         
        dtEmployee.Rows.Add(63, "Human2", 22000);         
        dtEmployee.Rows.Add(72, "Human3", 23000);         
        dtEmployee.Rows.Add(110,"Human4", 24000);           
        // sorting the datatable basedon salary in descending order        
        DataRow[] rows= dtEmployee.Select(string.Empty,"Salary desc");           
        //foreach datatable         
        foreach (DataRow row in rows)         
        { 
            Console.WriteLine(row["ID"].ToString() + ":" + row["Name"].ToString() + ":" + row["Salary"].ToString());         
        }           
        Console.ReadLine();     
    }   
}
于 2012-06-11T11:49:00.177 回答
0

数组示例:http: //msdn.microsoft.com/en-us/library/f6dh4x2h (VS.80).aspx

单个对象的示例:http: //msdn.microsoft.com/en-us/library/ydd48eyk

只需使用这样的东西:

DataTable dt = new DataTable();
DataRow dr = dt.Rows.Find(accntID);

希望这对您有所帮助。

于 2012-06-11T12:03:42.627 回答