views:

29

answers:

1
I have used linq to entities to basically create an anonymous type with properties

bookId and rating which I have grouped by bookId. all I need to do is take this and 

form an anonymous type which groups by bookId and gives the average rating for this bookid

so anonymous type results currently looklike:


bookid = 1, rating = 2
bookid = 1, rating = 4
bookid = 2, rating = 3
bookid = 3, rating = 5

and the results need to look like

bookid = 1, averagerating = 3 bookid = 2, averagerating = 4 bookid = 3, averagerating = 5

averagerating just based on the grouping.

thanks

A: 

Given an anonymous type named bookRatingList which contains an list of bookRatings (new {bookid = somevalue, rating = somevalue}) you can use the following code:

    var bookRatingAverageList = from book in bookRatingList
    orderby book.bookid
    group book by book.bookid
    into groupedList
    select new { BookId = groupedList.Key, 
                 AverageRating = groupedList.Average(b => b.rating)};

The result should be an array of anonymous typed objects with BookId and AverageRating properties and ordered by BookId.

Luis