Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting linq query to icollection

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

like image 629
bergin Avatar asked May 30 '10 15:05

bergin


People also ask

How does a LINQ query transform to a SQL query?

LINQ to SQL translates the queries you write into equivalent SQL queries and sends them to the server for processing. More specifically, your application uses the LINQ to SQL API to request query execution. The LINQ to SQL provider then transforms the query into SQL text and delegates execution to the ADO provider.

Which method of C #' s LINQ can be used to transform one type of parameter into another?

By using a LINQ query, you can use a source sequence as input and modify it in many ways to create a new output sequence. You can modify the sequence itself without modifying the elements themselves by sorting and grouping.

What is SelectMany in LINQ C#?

The SelectMany in LINQ is used to project each element of a sequence to an IEnumerable<T> and then flatten the resulting sequences into one sequence. That means the SelectMany operator combines the records from a sequence of results and then converts it into one result.

Which of the following can serve as a data source for a LINQ query in C #?

Types such as ArrayList that support the non-generic IEnumerable interface can also be used as a LINQ data source.


2 Answers

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>;
like image 167
Jason Avatar answered Sep 19 '22 15:09

Jason


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.

like image 34
Matthew Flaschen Avatar answered Sep 18 '22 15:09

Matthew Flaschen