tags:

views:

35

answers:

2

I have the following code:

List<T> list = new List<T>();

IEnumerable<T> query1 = ...
IEnumerable<T> query2 = ...
IEnumerable<T> query3 = ...

list.AddRange(query1.ToList<T>());
list.AddRange(query2.ToList<T>());
list.AddRange(query3.ToList<T>());

As far as I'm aware this will cause a trip to the database each time the ToList method is used on a query.

How would I combine the queries so that only one trip is made to the database?

+1  A: 

You might be able to union them.

list.AddRange( query1.Union(query2).Union(query3));
Alex Black
+1  A: 

If Union or Concat don't end up reducing the number of calls to the database, I would at least get rid of those ToList() calls. AddRange takes an IEnumerable, and your query is already IEnumerable. Calling ToList() on your query just means that your items get enumerated twice - once to convert the query to a List, and a second time to add the list to the main List.

Joel Mueller