如何从数据表中过滤特定值

时间:2012-06-11 11:42:35

标签: c# .net

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

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

3 个答案:

答案 0 :(得分:1)

三个选项:

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

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

var row = table.AsEnumerable()
               .FirstOrDefault(r => r.Field<string>("AccountID") == accountID);
if (row != null)
{
    // Use the row
}

答案 1 :(得分: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();     
    }   
}

答案 2 :(得分: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);

希望这能帮到你。