27

我需要将 linq 查询结果转换为列表。我尝试了以下代码:

var qry = from a in obj.tbCourses
                     select a;

List<course> lst = new List<course>();
lst = qry.ToList();

上述代码出现以下错误:

Cannot implicitly convert type 
System.Collections.Generic.List<Datalogiclayer.tbcourse> to
System.Collections.Generic.List<course>
4

5 回答 5

32

没必要做那么多工作。。

var query = from c in obj.tbCourses
        where ...
        select c;

然后你可以使用:

List<course> list_course= query.ToList<course>();

这对我来说可以。

于 2012-11-08T11:41:52.670 回答
30
List<course> = (from c in obj.tbCourses
                 select 
                new course(c)).toList();

您可以直接在调用时将实体对象转换为列表。有一些方法可以将其转换为不同的数据结构(列表、数组、字典、查找或字符串)

于 2013-11-20T22:19:42.880 回答
8

您需要以某种方式将每个tbcourse对象转换为course. 例如course,可以有一个构造函数,它采用tbcourse. 然后,您可以像这样编写查询:

var qry = from c in obj.tbCourses
          select new course(c);

List<course> lst = qry.ToList();
于 2012-04-26T12:48:16.357 回答
7

您需要使用select newLINQ 关键字将您的tbcourse实体显式转换为自定义类型course。示例select new

var q = from o in db.Orders
        where o.Products.ProductName.StartsWith("Asset") && 
              o.PaymentApproved == true
        select new { name   = o.Contacts.FirstName + " " +
                              o.Contacts.LastName, 
                     product = o.Products.ProductName, 
                     version = o.Products.Version + 
                              (o.Products.SubVersion * 0.1)
                   };

http://www.hookdonlinq.com/LINQtoSQL5MinuteOverview.ashx

于 2012-04-26T12:45:51.863 回答
4

您可以做的是将所有内容选择到一个新的 Course 实例中,然后将它们转换为 List。

var qry = from a in obj.tbCourses
                     select new Course() {
                         Course.Property = a.Property
                         ...
                     };

qry.toList<Course>();
于 2013-06-15T19:20:31.297 回答