Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert LINQ query result to List?

Tags:

linq

tolist

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>
like image 475
Brillia Avatar asked Apr 26 '12 12:04

Brillia


People also ask

How to convert LINQ result to class object?

Select(i => new CustomDeptList { DeptId = i. DepartmentID, DeptName = i.Name }). ToList(); "Select(i => new" without your class name will return an IEnumerable of Anonymous Type which you are sending to a List<T> with the ToList().

Which of the following methods convert collections to list instances in Linq?

ToList() convert the collection of data into the list.


4 Answers

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.

like image 56
dellgg Avatar answered Oct 15 '22 01:10

dellgg


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)

like image 29
goggles1200 Avatar answered Oct 15 '22 00:10

goggles1200


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();
like image 23
Thomas Levesque Avatar answered Oct 15 '22 02:10

Thomas Levesque


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

like image 21
msigman Avatar answered Oct 15 '22 02:10

msigman