views:

36

answers:

3

Hi,

I'have a table with movies, which has an integer attribute called ranking. I'd now like to retrieve the average ranking from all movies containing a certain actor.

Dim q2 = (From p In dc.Movies Where p.actlist.Contains(actor.name) Select p.ranking).Average()

This query doesn't work - Overload resolution failed because no accessible "Average" accepts this number of arguments. Without the Where-Clause it runs fine.

How to combine the Average function with Where-clause? I couldn't find any helpful example on MSDN and the internet ..

A: 

Possibly no results so it can give no average; try

Dim q2 = (From p In dc.Movies Where p.actlist.Contains(actor.name) Select p.ranking).Count() == 0 ? 0 : (From p In dc.Movies Where p.actlist.Contains(actor.name) Select p.ranking).Average();
Jan-Frederik Carl
That would cause a runtime error (Sequence contains no elements), not a compile-time error.
Ronald Wildenberg
A: 

Can you try the following code:

Dim avgRanking = (From m in dc.Movies _
                  Where m.actlist.Contains(actor.Name) _
                  Select m.ranking).Average(Function(a) Convert.ToInt32(a))

And this should also work:

Dim avgRanking = (From m in dc.Movies _
                  Where m.actlist.Contains(actor.Name) _
                  Select CInt(m.ranking)).Average()

The problem is the type of Movie.ranking. The result of your query is and IEnumerable of tinyint. There is no overload of Average for this.

Ronald Wildenberg
This one is not working, build failed with error 'Name' is not a member of 'Char'. :-( Actlist is simply a string with xml-formatted content.
AKR715
In that case my answer is not very useful :)
Ronald Wildenberg
Do you have any idea how to achieve my desired result?
AKR715
Type of Movie.ranking is tinyint.Query with Enumerable.Average breaks with "Overload resolution failed because noaccessible 'Average' can be called without a narrowing conversion ..."
AKR715
I updated my answer with what I think is the solution.
Ronald Wildenberg
A: 

I've figured out by myself:

Dim q3 = (From a In dc.Movies Where a.actlist.Contains(actor.name) Select a).Average(Function(r) r.ranking)

But this one throws an execption if an actor isn't in any movie. So I had to put it in try..cast.

AKR715