将LINQ查询的结果保存到列表中

时间:2015-07-30 00:18:30

标签: linq tolist

我正在尝试创建处理程序以将LINQ查询的结果保存到列表以及我到达的内容

public static List<string> Get()
{
    LesamisContainer LC = new LesamisContainer();

    List<string> list = (from pb in LC.PayBills
                         join c in LC.Customers on pb.CustomerId equals c.Id
                         join d in LC.Departments on pb.DepartmentId equals d.Id
                         select new { pb.Id, c.FullName, d.Name, pb.Discount, pb.TotalAmount, pb.Details, pb.Date, pb.CustomerId, pb.DepartmentId } into x
                         select x).Tolist();
    return list;
}

但我得到了这个例外

http://i60.tinypic.com/2lxu2o.png

  

无法将类型'System.Collections.Generic.List'转换为'System.Collections.Generic.List'

2 个答案:

答案 0 :(得分:2)

您正在使用

创建匿名类型
select new { pb.Id, c.FullName, d.Name, pb.Discount, pb.TotalAmount, pb.Details, pb.Date, pb.CustomerId, pb.DepartmentId } into x

select x只返回此类型。要获得List<string>,您需要从此处返回属性,例如:select x.FullName

这将是一种非常奇怪的做事方式,可能不是你真正想要的。我认为你实际上并不想要List<string>

在这种情况下,由于您从方法返回结果,因此应该声明它而不是匿名:

public class PayBillModel 
{
    public int Id {get;set;}
    ...
}

然后

select new PayBillModel() { pb.Id, c.FullName, d.Name, pb.Discount, pb.TotalAmount, pb.Details, pb.Date, pb.CustomerId, pb.DepartmentId }

这样,您最终得到List<PayBillModel>

答案 1 :(得分:1)

您获得了多种类型。尝试将List类型更改为object,而不是string

List<object> list = (from pb in LC.PayBills
                         join c in LC.Customers on pb.CustomerId equals c.Id
                         join d in LC.Departments on pb.DepartmentId equals d.Id
                         select new { pb.Id, c.FullName, d.Name, pb.Discount, pb.TotalAmount, pb.Details, pb.Date, pb.CustomerId, pb.DepartmentId } into x
                         select x).Tolist();

然后您可以通过以下方式浏览列表:

foreach (object item in list)
{
   if (item is pb.Id)
   { 
      //do something
   }

   //or
   //if (item.GetType() == typeof(PayBills)) { }
}