Reputation: 572
I have cobbled together what I thought would have been a solution to what I wanted to do based on other threads on here on this topic (return a specific number of items from a list) but I think my syntax is a little of and it is not allowing me to sum the items I have taken.
Here is what I have:
public decimal average_of_items_examples(List<Car> cars)
{
if (cars == null)
{
return 0;
}
else if (cars.Count == 0)
{
return 0;
}
else
{
return cars.OrderBy(x => x.SuggestedRetailPrice).Take(3).Average();
}
}
I appreciate any help and appreciate explanations.
EDIT: Sorry I forgot to add why I have the OrderBy part. I only want the average of the 3 less expensive cars.
NOTE: I can not change the type "decimal" as this is how the exercise was written.
Upvotes: 1
Views: 924
Reputation: 23975
Both:
cars.OrderBy(x => x.SuggestedRetailPrice).Take(3).Select(z => z.SuggestedRetailPrice).Average();
and:
cars.Select(z => z.SuggestedRetailPrice).OrderBy(x => x).Take(3).Average();
will do what you need.
They are both basically the same.
Upvotes: 3
Reputation: 13399
.Average(x => x.SuggestedRetailPrice)
You have to specify the property you want to get average of since the collection is for Car
objects
Upvotes: 3