I have a table let says Products which contains two column(ProductId, Price). I am getting list of product Ids from client(IOS, Android). Instead of iterating over the list and getting the price one by one and then calculate average, Is there any better way to do so?
Asked
Active
Viewed 329 times
2 Answers
2
If I understand correctly, you have a list with product Ids and want to get the average price for the selected products. You can use a combination of Contains
and Average
like this:
List<int> productIds = ...;
var averagePrice = db.Products
.Where(p => productIds.Contains(p.ProductId))
.Select(p => p.Price)
.DefaultIfEmpty()
.Average();
The Select
followed by DefaultIfEmpty
is needed to avoid exception when the filtered set contains no records.
Update: As per comment, getting several aggregates with a single query is also possible by using group by
constant construct:
var info = (from p in db.Products
where productIds.Contains(p.ProductId)
group p by 0 into g // any constant would work
select new
{
MinPrice = g.Min(p => p.Price),
MaxPrice = g.Max(p => p.Price),
AveragePrice = g.Average(p => p.Price),
}).FirstOrDefault();
var minPrice = info != null ? info.MinPrice : 0;
var maxPrice = info != null ? info.MaxPrice : 0;
var averagePrice = info != null ? info.AveragePrice : 0;

Ivan Stoev
- 195,425
- 15
- 312
- 343
-
Thanks Ivan, Just wondering, Is It possible to get Min, Max and Average in a single query? – Jyotish Singh Jun 15 '16 at 12:42
-
I think it's possible, although not very natural in LINQ. As I remember, needs using `group by` *constant* in order to be able to produce multiple aggregates. – Ivan Stoev Jun 15 '16 at 13:23
-
Thanks Ivan once again :) – Jyotish Singh Jun 16 '16 at 09:37