如何在LINQ中返回连接语句

时间:2015-10-13 05:46:54

标签: c# linq join

我想将结果3返回给主方法

 var result = (from od in orders
        join em in employees on od.EmployeeID equals em.EmployeeID
        join ct in customers on od.CustomerID equals ct.CustomerID
        //orderby em.EmployeeID
        select new
        {
            od.OrderID,
            od.ShipCountry,
            ct.CompanyName,
            ct.ContactName,
            FullName = em.FirstName + ' '+ em.LastName, 
        });


 var newOrders = result.OrderBy("OrderID DESC");

 var result3 = newOrders
    .ToList()
    .Skip(rowsPerPage * (page-1))
    .Take(rowsPerPage);

 return result3;
}

 public class MyJoin {
 public int OrderID { get; set; }
 public DateTime OrderDate { get; set; }
 public string ShipCountry { get; set; }
 public string CompanyName { get; set; }
 public string ContactName { get; set; }
 public string EmployeeName { get; set; }
 }

我不确定如何将其作为简单的

返回
return result3;

不行,我收到错误

  

无法隐式转换类型   System.Collections.Generic.List<AnonymousType#1>来   System.Collections.Generic.List<UserQuery.MyJoin>

3 个答案:

答案 0 :(得分:4)

这不起作用,因为在这里:

select new
{
    od.OrderID,
    od.ShipCountry,
    ct.CompanyName,
    ct.ContactName,
    FullName = em.FirstName + ' '+ em.LastName, 
}

您正在创建新类型 - &gt; AnonymouseType,它不是您期望在函数中返回的MyJoin类型。只需使用:

select new UserQuery.MyJoin
{
   OrderID = od.OrderID,
   ...
}

当然,您需要填写MyJoin班级的字段。

答案 1 :(得分:0)

您无法从函数调用中返回匿名类型。

您必须明确定义您期望的类型,然后

var result = (from od in orders
    join em in employees on od.EmployeeID equals em.EmployeeID
    join ct in customers on od.CustomerID equals ct.CustomerID
    //orderby em.EmployeeID
    select new UserQuery.MyJoin
    {
        od.OrderID,
        od.ShipCountry,
        ct.CompanyName,
        ct.ContactName,
        FullName = em.FirstName + ' '+ em.LastName, 
    });


var newOrders = result.OrderBy("OrderID DESC");

var result3 = newOrders
.Skip(rowsPerPage * (page-1))
.Take(rowsPerPage);
.ToList()

return result3;

请注意,如果这是Linq to Objects,或者调用者可以使用DbContext,则不需要实现结果(不需要.ToList())。

答案 2 :(得分:0)

指定类型 -

在你的情况下

IQueryable<UserQuery.MyJoin> result = (from od in orders
    join em in employees on od.EmployeeID equals em.EmployeeID
    join ct in customers on od.CustomerID equals ct.CustomerID
    //orderby em.EmployeeID
    select new UserQuery.MyJoin
    {
        od.OrderID,
        od.ShipCountry,
        ct.CompanyName,
        ct.ContactName,
        FullName = em.FirstName + ' '+ em.LastName, 
    });