Search code examples
c#linqaverage

How to get average of list within lists using linq?


I am creating a method that will get a list of business objects that tie for the highest average rating. The method starts with a list of businesses. Each business contains a list of review objects that contain a rating (int).

To illustrate:

list<Review> reviews = curtBusiness.getReviews();
reviews[1].GetRating();

Using a for loop I could find this easily, unfortunately however I am required to use linq, something I have almost no skills at.

Can anyone help me make a linq statement for this query or for a similar query?

Update:

I think I may have stumbled into a solution

 double average = busInCat.Max(b=> b.GetReviews().Average(r => r.getRateing()));
        return busInCat.Where(b => b.GetReviews().Average(r => r.getRateing()) == average).ToList();

If the above code is correct then it first finds the max average of ratings in the first line.

Then in the second line returns a list of of the businesses that have that average rating. Can anyone confirm this is what the linq expressions is doing?


Solution

  • I have tested the solution I put in the update:

    double average = busInCat.Max(b=> b.GetReviews().Average(r => r.getRateing()));
    return busInCat.Where(b => b.GetReviews().Average(r => r.getRateing()) == average).T
    

    The above code does indeed work as intended.