将Linq-to-DataSet查询的结果加载到datatable中

时间:2009-12-09 20:50:52

标签: c# linq linq-to-dataset

我有一个linq to dataset查询,它连接两个表并从每个表中提取所需的参数。我需要将它们放入DataTable中以绑定到DataGridView。我在MSDN上执行此操作的示例是从单个表中获取单个值的一个简单示例,但是当我尝试更改查询以遵循它时,我无法执行此操作。 CopyToDataTable()方法要求将查询分配给IEnumerable<DataRow>,但是当我这样做时,我被告知需要进行明确的演示;但是演员在运行时失败,但有例外:

  

无法转换类型为'd__61`4的对象[System.Data.DataRow,System.Data.DataRow,System.Int32,&lt;&gt; f__AnonymousType0`1 [System.Int32]]'   输入   'System.Collections.Generic.IEnumerable`1 [的System.Data.DataRow]'。

原始工作查询:

var query = MyDataSet.Table1.AsEnumerable().Join(MyDataSet.Table2.AsEnumerable(),
    table1 => table1.Field<Int32>("Table1_Id"),
    table2 => table2.Field<Int32>("Table1_Id"),
    (table1, table2) => new
    {
        Table1ID = table1.Field<Int32>("Table1_Id")
        //Other parameters commented out to simplify the example
    });

使用显式强制转换的非工作查询:

IEnumerable<DataRow> query = (IEnumerable<DataRow>)MyDataSet.Table1.AsEnumerable().Join(MyDataSet.Table2.AsEnumerable(),
    table1 => table1.Field<Int32>("Table1_Id"),
    table2 => table2.Field<Int32>("Table1_Id"),
    (table1, table2) => new
    {
        Table1ID = table1.Field<Int32>("Table1_Id")
        //Other parameters commented out to simplify the example
    });

3 个答案:

答案 0 :(得分:2)

在这两种情况下,您都要创建一个新的“匿名类型”来存储结果。

要使第二个工作,你需要像:

var query = ... => new DataRow() 
{
});

除了因为DataRow没有公共构造函数而无法以这种方式初始化之外无效。

所以,使用第一个并迭代结果(注意我在这里猜一点,你必须先设置table3的列):

foreach (var row in query)
{
   var r = table3.NewRow();
   r["Table1ID"] = row.Table1ID;
   r["Table2ID"] = row.Table1ID;                
}

编辑:

 var query = ...;  // step 1

 query = query.ToList();  // add this,  step 2

 foreach(...) { }  // step 3

如果您单独计算上述3个步骤,您可能会看到第2步花费的时间最多。

答案 1 :(得分:0)

嗨,这是另一种方法..

        //I have created datatable Address having AddressID<int32>,Name-srting,LastName-string
        DataSet ds= new DataSet();
        ds.Tables["Address"].Rows.Add(new object[] { 1, "Priya", "Patel" });
        ds.Tables["Address"].Rows.Add(new object[] { 2, "Bunty", "Rayapati" });
        ds.Tables["Address"].Rows.Add(new object[] { 3, "Birva", "Parikh" });
        //i have created Datatable AddressType having AddressTypeID int32 and State- string
        ds.Tables["AddressType"].Rows.Add(new object[] { 1, "Virginia" });
        ds.Tables["AddressType"].Rows.Add(new object[] { 2, "Nebraska" });
        ds.Tables["AddressType"].Rows.Add(new object[] { 3, "Philadeplhia" });

        DataTable dt1 = ds.Address.CopyToDataTable(); 
        DataTable dt2 = ds.AddressType.CopyToDataTable();
        DataTable dt3 = new DataTable();

        var query = dt1.AsEnumerable().Join(dt2.AsEnumerable(),
            dmt1 => dmt1.Field<Int32>("AddressID"),
                dmt2 => dmt2.Field<Int32>("AddressTypeID"),
        (dmt1, dmt2) => new 
        {
            Table1ID = dmt1.Field<Int32>("AddressID")
            //Other parameters commented out to simplify the example
        });
        query.ToList();
        //FullAddress is my third Datatable is having AID
        foreach (var row in query)
        {
            var r = ds.FullAddress.NewRow();
            r["AID"] = row.Table1ID;
            ds.FullAddress.Rows.Add(r.ItemArray);

        }

答案 2 :(得分:0)

我遇到了这样的错误,因为LINQ查询编译器中的after many joins statements create new type that concatenate all your models

所以很难直接投入

但是你知道结果只包含一个特定的模型,你可以再做一步来帮助编译器转换它

MyListOfTypeIEnumerable.ToArray()

看看我的问题并ToArray()解决它

public static IList<Letter> GetDepartmentLetters(int departmentId)
    {
        IEnumerable<Letter> allDepartmentLetters = from allLetter in LetterService.GetAllLetters()
            join allUser in UserService.GetAllUsers() on allLetter.EmployeeID equals allUser.ID into usersGroub
            from user in usersGroub.DefaultIfEmpty()
            join allDepartment in DepartmentService.GetAllDepartments() on user.DepartmentID equals allDepartment.ID
            where allDepartment.ID == departmentId
            select allLetter;
        return allDepartmentLetters.ToArray();
    }