LinQ获得具有平均数错误的不同字段

时间:2017-02-11 11:08:51

标签: c# mysql linq

我遇到“预期类型”错误,我不明白为什么。

我的查询只是将3个表链接在一起,同时尝试获取不同的包和平均评分数。

结果应该是这样的

| PackageName | Average Rating |
|    SG       |        4       |
|    USA      |        4       |    
        IQueryable<Recommendation> recommendationQuery = db.Recommendations;
        IQueryable<Booking> bookingQuery = db.Bookings;
        IQueryable<Package> packageQuery = db.Packages;

        recommendationQuery =  (from recommendationItem in recommendationQuery
                               join bookingItem in bookingQuery
                               on recommendationItem.BookingId equals bookingItem.BookingId
                               join packageItem in packageQuery
                               on recommendationItem.Booking.PackageId equals packageItem.PackageId
                               select recommendationItem).GroupBy(c => c.Booking.Package.PackageTitle)
                               .Select(c => new ( c.Key, c.Average(d=>d.Rating)));

预期类型出现在.Select中(c =&gt; new(.....

我可以知道我是否错误地查询了它?

由于

1)我内心加入了我所有的3张桌子

2)假设我已加入所有表,我尝试按PackageName对它们进行分组,以将名称与一个名称区分开来

3)我试图选择同一包装的平均等级。

是否有更好的解决方案?

database class diagram

Solution error

1 个答案:

答案 0 :(得分:1)

您需要将结果存储回新变量以匹配您的新类型:

var results = from recommendationItem in recommendationQuery
                join bookingItem in bookingQuery
                on recommendationItem.BookingId equals bookingItem.BookingId
                join packageItem in packageQuery
                on recommendationItem.Booking.PackageId equals packageItem.PackageId
                group recommendationItem
                by recommendationItem.Booking.Package.PackageTitle
                into grp
                select new
                {
                    PackageName = grp.Key,
                    AverageRating = grp.Average(d => d.Rating)
                };