我正在尝试获取主数据表,并将数据的子集从其中拉入另一个表。我无法弄清楚如何使我的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 [],我真的希望它在一个表对象中。
答案 0 :(得分:2)
你需要:
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
值。