How to convert LINQ query result to List?

前端 未结 5 1435
花落未央
花落未央 2020-12-06 09:51

I need to convert linq query result to list. I tried the following code:

var qry = from a in obj.tbCourses
                    


        
相关标签:
5条回答
  • 2020-12-06 09:52

    What you can do is select everything into a new instance of Course, and afterwards convert them to a List.

    var qry = from a in obj.tbCourses
                         select new Course() {
                             Course.Property = a.Property
                             ...
                         };
    
    qry.toList<Course>();
    
    0 讨论(0)
  • 2020-12-06 10:10

    No need to do so much works..

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

    Then you can use:

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

    It works fine for me.

    0 讨论(0)
  • 2020-12-06 10:10

    You need to somehow convert each tbcourse object to an instance of course. For instance course could have a constructor that takes a tbcourse. You could then write the query like this:

    var qry = from c in obj.tbCourses
              select new course(c);
    
    List<course> lst = qry.ToList();
    
    0 讨论(0)
  • 2020-12-06 10:13

    You need to use the select new LINQ keyword to explicitly convert your tbcourseentity into the custom type course. Example of 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.hookedonlinq.com/LINQtoSQL5MinuteOverview.ashx

    0 讨论(0)
  • 2020-12-06 10:16
    List<course> = (from c in obj.tbCourses
                     select 
                    new course(c)).toList();
    

    You can convert the entity object to a list directly on the call. There are methods to converting it to different data struct (list, array, dictionary, lookup, or string)

    0 讨论(0)
提交回复
热议问题