converting linq query to icollection

bergin picture bergin · May 30, 2010 · Viewed 7.7k times · Source

I need to take the results of a query:

 var query = from m in db.SoilSamplingSubJobs where m.order_id == id select m;

and prepare as an ICollection so that I can have something like

 ICollection<SoilSamplingSubJob> subjobs

at the moment I create a list, which isnt appropriate to my needs:

query.ToList();

what do I do - is it query.ToIcollection() ?

Answer

Jason picture Jason · May 30, 2010

List is an ICollection. You can change you query.ToList() code to the following.

query.ToList() as ICollection<SoilSamplingSubJob>;

You question sounds like this query is returned as a function result. If this is the case remember that the Linq to SQL objects are connected by default so you will need to manage where your database context get opened and closed. Alternatively you can create DTOs (Data Transfer Objects) that hold the data you want to use in the rest of your program. These objects can fit into your object hierarchy any way you want.

You can also create these DTOs as part of the query.

var query = from m in db.SoilSamplingSubJobs where m.order_id == id
            select new SubJobDTO {
                OrderNumber = m.order_id
            };
return query.ToList() as ICollection<SubJobDTO>;