开发者

LINQ Average function arguments

开发者 https://www.devze.com 2023-03-28 22:47 出处:网络
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:

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 Avg开发者_JAVA技巧Cuisine = 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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消