数据表到数据表 linq 过滤器

datatable to datatable linq filter

我正在尝试获取一个主要数据table,并将其中的一个数据子集拉入另一个table。我不知道如何让我的 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");

但是 returns 我是一个 DataRow[],我真的希望它位于 table 对象中。

你需要:

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 值。