Question

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() ?

Was it helpful?

Solution

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>;

OTHER TIPS

Since, query implements IEnumerable, you can pass it to the constructor of the collection of your choice. ICollection is an interface, implemented by several classes (including List<T>, which ToList returns) with different performance characteristics.

With slightly different syntax, you can do something like this as well that can cut down on what goes into the ICollection. This type of approach is great for Angular and MVC when you have a huge table but only want to load some props into the cshtml page:

ICollection<SoilSamplingSubJob> samples = dbContext.GetQuery().Where(m => m.order_id == id)
.AsEnumerable().Select(s => new
            {
                Id = s.order_id,
                CustomProperty = s.some_thing
            }).ToList() as ICollection<SoilSamplingSubJob>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top