27

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

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

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

The following error occurred for the above code:

Cannot implicitly convert type 
System.Collections.Generic.List<Datalogiclayer.tbcourse> to
System.Collections.Generic.List<course>
Marijn
  • 9,846
  • 4
  • 52
  • 75
Brillia
  • 1,243
  • 2
  • 13
  • 21

5 Answers5

31

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.

j0k
  • 21,914
  • 28
  • 75
  • 84
dellgg
  • 446
  • 4
  • 11
29
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)

IvanH
  • 4,686
  • 13
  • 55
  • 71
goggles1200
  • 291
  • 3
  • 2
  • IMHO this is the best answer. It is not only single command, but it also illustrates that `from ... select ...` linq syntax is still keeping its meaning equivalent to standard form (`tbCourses.Select()`) – miroxlav Oct 26 '14 at 00:01
8

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();
Thomas Levesque
  • 270,447
  • 59
  • 580
  • 726
  • This is creative! But, it does have one drawback that your models project would now have a dependency to your data repository. While this would be fine in a smaller project, depending on your architecture and separation of concers, this could be a problem. – msigman Apr 26 '12 at 12:50
7

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

msigman
  • 4,364
  • 2
  • 17
  • 29
3

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>();
Kao
  • 2,182
  • 2
  • 21
  • 30