数据表到数据表的linq过滤器



我试图采取一个主数据表,并从它拉到另一个表的数据子集。我不知道如何得到我的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值。

相关内容

  • 没有找到相关文章

最新更新