views:

57

answers:

2

I'm starting with linqToSql and I still have some problems making my queries.

For example, I want to retrieve in the same query two values, a subset of elements, and an integer with the count of the elements. This is how I did it separately:

  int totalElements;
  IEnumerable<ClsTax> result;
  result = (from t in db.tax 
           select new ClsTax { Tax = t.tax1, Increase = t.increase }).Take(25);

  totalElements = (from t in db.tax 
             select new ClsTax { Tax = t.tax1, Increase = t.increase }).Count();

As you can see, I can't use result.count() because I used Take(25) to obtain only the firsts 25 elements, and I want to know how many elements are in the database.

Are there any way to obtain both values using only one linq query?

Thanks!

+1  A: 

Try this:

var result = (from t in db.tax group t by t.ID into g select new { Tax = g.First().tax1, Increate = t.First().Increase, TotalElements = g.Count() });
k0ni
I can't make it work. Could you explain me your code a little, please? I don't want a fish, I want a fishing rod! :D Thanks!
Jonathan
This code selects an anonymous class/type with all informations you need + the count of the items
k0ni
+3  A: 

How about:

var all = (from t in db.tax select new ClsTax { Tax = t.tax1, Increase = t.increase });
var count = all.Count();
var result = all.Take(25);

bit simpler?

CodeMonkey
Yes, a bit simpler, but I want to minimize the database calls and traffic. 'All' could contain many records.
Jonathan
All will not contain many records. This is because of deferred execution. Download LinqPad, try running this query and look at the generate SQL. Two queries will be generated - the first will be a SELECT COUNT query and the second a SELECT TOP 25 query.
Winston Smith
@joe: so... then it's a simple and and elegant solution at the same time. I will accept it. Thaks to you and to CodeMonkey. I will take your advide and download LinqPad.
Jonathan