Susan
Susan

Reputation: 1832

LINQ Average function arguments

I'm stumped on how to get my average UI layer function working. First, here is the function in my Data Access Layer which appears to be working fine:

public class AvgReviewInfo
{
   public int AvgReviewId { get; set; }
   public int AvgNum { get; set; }
   public double AvgTags { get; set; }
}

public IEnumerable<AvgReviewInfo> getAvgCuisine(int RestID)
{
   // Return the count of the average number of reviews for a specific restaurant ID
   var AvgCuisine = from REVIEW in db.REVIEWs
                    where REVIEW.REST_ID == RestID
                    group REVIEW by REVIEW.REVIEW_ID into t
                    select new AvgReviewInfo { 
                             AvgReviewId = t.Key, 
                             AvgNum = t.Count(),
                             AvgTags = t.Average(c => c.FOOD_ID)   };

   return AvgCuisine;
}

I trying to populate a text box with the AVERAGE in my UI layer using the the following code:

BLgetDetails obj2 = new BLgetDetails();
var AvgCuisine = obj2.getAvgCuisine(restid);
lblAvgReviews.Text = AvgCuisine.Average().ToString();

I don't understand from the hints by intellisense what arguments are needed. I know this must be something simple ;O((

Thanks in advance!

Upvotes: 2

Views: 1030

Answers (1)

James Harris
James Harris

Reputation: 1914

The Func<T,int> or Func<T,double> overloads of IEnumerable.Average need you to supply a lambda function which selects which field of "AvgReviewInfo" you want to calculate the average of.

Basically you are supplying a function that does something for every item in the collection.

For example, to calculate the average of the AvgNum field you would use

lblAvgReviews.Text = AvgCuisine.Average(a=>a.AvgNum).ToString();

Where the left hand side a => means literally given an individual AvgReviewInfo which we are calling a, the right hand side a.AvgNum means return the value of AvgNum

This lamba function is run over every item in the IEnumerable and the resulting average is calculated.

Upvotes: 1

Related Questions