データ テーブルに 5 つの行 (列 AccountId、Name、Email、Address) があり、5 つの行すべてに異なる AccountID があるため、AccountId に基づいて特定の行を取得したいと考えています。AccountID に基づいてフィルタリングしたい。つまり、AccountId に基づいて処理するには、Data テーブルから 1 行だけ必要です。
渡した AccountId を含むデータ テーブルから特定の行を取得するにはどうすればよいですか?
3 つのオプション:
DataTable.Select
して、フィルター式を提供します個人的には、最後のオプション (LINQ) を使用することをお勧めします。
var row = table.AsEnumerable()
.FirstOrDefault(r => r.Field<string>("AccountID") == accountID);
if (row != null)
{
// Use the row
}
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();
}
}
配列の例: 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);
これがお役に立てば幸いです。