如何从数据表中选择所有字段

时间:2012-05-16 09:36:03

标签: c# linq select join datatable

如何从数据表中选择所有字段?例如:

var common = from c in dt1.AsEnumerable()
             join x in dt2.AsEnumerable() on c.Field<int>("ID") equals
             x.Field<int>("ID")
             select
             new object[]
             {
                 c["Col1"], x["NameCol1"], x["NameCol2"], x["NameCol3"], x["NameCol4"]

             };

如何选择x的所有字段? (如果x有20个列,我不想写所有字段的名称)

1 个答案:

答案 0 :(得分:0)

也许这会有所帮助:

        var customers = new DataTable();
        customers.Columns.Add("ID", typeof(int));
        customers.Columns.Add("Name");

        customers.Rows.Add(1, "Tom");
        customers.Rows.Add(2, "Dick");
        customers.Rows.Add(3, "Harry");

        var purchases = new DataTable();
        purchases.Columns.Add("ID");
        purchases.Columns.Add("Description");
        purchases.Columns.Add("PurchaseID", typeof(int));

        purchases.Rows.Add(1, "Bike", 1);
        purchases.Rows.Add(2, "Holiday", 1);
        purchases.Rows.Add(3, "Bike", 2);
        purchases.Rows.Add(4, "Car", 3);

        var query = customers.AsEnumerable().Join(purchases.AsEnumerable(),
                                    cust => cust.Field<int>("ID"),
                                    purch => purch.Field<int>("PurchaseID"),
                                    (cust, purch) =>
                                    {
                                        var res = new List<object>();
                                        res.AddRange(cust.ItemArray);
                                        res.AddRange(purch.ItemArray);
                                        return res.ToArray();
                                    }
                                    );