[英]datatable to datatable linq filter
我正在嘗試獲取一個主數據表,並將數據的子集從其中拉到另一個表中。 我不知道如何使我的LINQ語法正確。
static void Main(string[] args)
{
Console.WriteLine("start...");
DataTable dt = new DataTable();
dt.Columns.Add("fn", typeof(string));
dt.Columns.Add("ln", typeof(string));
dt.Columns.Add("EN", typeof(int));
dt.Columns.Add("Role", typeof(string));
Object[] rows = {
new Object[]{"Jane","Smith",123456,"Admin"},
new Object[]{"Jane","Smith",123456,"Test"},
new Object[]{"Jane","Smith",123456,"QA"},
new Object[]{"John","Doe",23456,"Admin"},
new Object[]{"John","Doe",23456,"Test"},
new Object[]{"John","Doe",23456,"Manager"},
new Object[]{"John","Doe",23456,"Approver"},
new Object[]{"Princess","Peach",12345,"Admin"},
new Object[]{"Princess","Peach",12345,"Test"},
new Object[]{"Princess","Peach",12345,"QA"}
};
foreach(Object[] row in rows)
{
dt.Rows.Add(row);
}
DataTable o = dt.AsEnumerable()
.Where(x => x.Field<string>("EN") == 123456)
.CopyToDataTable();
for(int i =0; i <o.Rows.Count-1; ++i)
{
for(int x=0; x<o.Columns.Count; ++x)
{
Console.Write("{0}\t", o.Rows[i][x].ToString());
}
Console.WriteLine();
}
Console.WriteLine("fin...");
Console.ReadLine();
}
因此,在結果集中我想要的是Jane Smith的記錄。 我也嘗試使用
DataTable.Select("EN = 123456");
但這返回了一個DataRow [],我真的希望它位於表對象中。
你需要:
DataTable o = dt.AsEnumerable()
.Where(x => x.Field<int>("EN") == 123456)
.CopyToDataTable();
由於您輸入的字段是int
。
您還可以比較名字和姓氏,例如:
DataTable o = dt.AsEnumerable()
.Where(x => x.Field<string>("fn") == "Jane" &&
x.Field<string>("ln") == "Smith")
.CopyToDataTable();
如果要執行不區分大小寫的比較,請使用String.Equals
重載並提供適當的StringComparison
值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.