Skip to content
Advertisement

How to get average value using LEFT JOIN in LINQ and Lambda

I want to display each book average rating with its publisher using LINQ and Lambda.

Here’s my book list

First, i Join Book list with Publisher list using this query

Then, i try to use left join with BookTransaction list to get detail rating for each book. Here’s my BookTransaction list.

and here’s my query

in that query, i got the error saying that “‘Object reference not set to an instance of an object.’ bt was null.”

I tried using different approach, but the result it just the same error.

Can someone tell me where i was wrong? When i deleted the DefaultIfEmpty function, it can display the data but only where both list have the bookId value included, like this

I expect the result of the query just like this

Advertisement

Answer

Linq has an Average Method. You can call it on a collection of numeric values, or for a collection of objects you can pass it the property name to average. You can also call GroupBy to create key<->collection pairs.

So you can group your data by the BookId and find the average rating.

Assuming the following

Then

Gives the following output in the C# interactive console:

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement