Linq to Entities在预定义的分组中平均

时间:2009-06-29 19:12:55

标签: c# .net data-structures

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,平均值= 3    bookid = 2,平均值= 4    bookid = 3,平均值= 5

仅根据分组进行平均。

感谢

1 个答案:

答案 0 :(得分:1)

给定名为bookRatingList的匿名类型,其中包含bookRatings列表(new {bookid = somevalue,rating = somevalue}),您可以使用以下代码:

    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)};

结果应该是具有BookId和AverageRating属性并按BookId排序的匿名类型对象数组。