簡體   English   中英

如何從數據表中過濾特定值

[英]How to filter a specific value from a data table

我的數據表中有五行(帶有AccountId,Name,Email,Address列),我想基於AccountId獲得特定的行,因為所有五行都有不同的AccountID。 我想根據AccountID對其進行過濾。 我的意思是,我只需要從數據表中獲取一行就可以基於AccountId進行處理。

如何從包含已傳遞的AccountId的數據表中獲得特定行?

三種選擇:

  • 使用DataTable.Select ,提供過濾器表達式
  • 自己遍歷行
  • 使用帶有數據表擴展名的LINQ

我個人建議使用最后一個選項(LINQ):

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

您是否研究過DataTable.Select()方法?

http://msdn.microsoft.com/zh-CN/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();     
    }   
}

數組示例: http : //msdn.microsoft.com/zh-cn/library/f6dh4x2h(VS.80).aspx

具有單個對象的示例: http : //msdn.microsoft.com/zh-cn/library/ydd48eyk

只需使用以下內容:

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

希望這對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM