Linq: OrderBy Sum of several fields

I am trying to create a linq expression in which I can WRITE the number of comments on an event, as well as SUM the number of votes. Here is what I have, but I am not getting the corresponding results.

My example runs in VB.Net, but I can also deal with examples in C #.

    Public Function GetHotEvents(ByVal skip As Integer) As List(Of Domain.Event) Implements IEventService.GetHotEvents
        ''# Our order by sequence just takes the number of votes and multiplies
        ''# it by two. Then takes the number of comments and adds it to the
        ''# vote count.  This way up-voted events will climb to the top while
        ''# down-voted events will fall to the bottom.  Comments also add to
        ''# the "hotness" of the event.
        Return _EventRepository.Read() _
            .Where(Function(e) e.EventDate >= Date.Today) _
            .OrderBy(Function(e) (((e.EventVotes.Sum(Function(s) s.Vote)) * 2) + (e.Comments.Count))) _
            .Skip(skip) _
            .Take(5) _
            .ToList()
    End Function

What I did to test this has ZERO comments for all events and crowds out the ONE event. This event "should" float to the top, but it does not exist.

Any help would be greatly appreciated.

change

I tried to create an expression in LinqPad, but unfortunately it made an error (note: this error does not get into my code)

, "OrderBy" :      'Public Function OrderBy (Of TKey) (keySelector As System.Linq.Expressions.Expression( System.Func( LINQPad.User.Events, TKey))) As System.Linq.IOrderedQueryable( LINQPad.User.Events), 'System.Linq.Queryable': '' "LINQPad.User.Events".      'Public Function OrderBy (Of TKey) (keySelector As System.Linq.Expressions.Expression( System.Func( LINQPad.User.Events, TKey))) As System.Linq.IOrderedQueryable( LINQPad.User.Events), 'System.Linq.Queryable': () . .      'Public Function OrderBy (Of TKey) (keySelector As System.Func( LINQPad.User.Events, TKey)) As System.Linq.IOrderedEnumerable( LINQPad.User.Events), 'System.Linq.Enumerable': '' 'LINQPad.User.Events'.      'Public Function OrderBy (Of TKey) (keySelector As System.Func( LINQPad.User.Events, TKey)) As System.Linq.IOrderedEnumerable( LINQPad.User.Events), 'System.Linq.Enumerable': () . .

2

SQL

DECLARE @p0 Int = 2    

SELECT *
FROM [dbo].[Events] AS [t0]
ORDER BY (((
    SELECT SUM([t1].[Vote])
    FROM [dbo].[EventVotes] AS [t1]
    WHERE [t1].[EventID] = [t0].[ID]
    )) * @p0) + ((
    SELECT COUNT(*)
    FROM [dbo].[Comments] AS [t2]
    WHERE [t2].[EventID] = [t0].[ID]
    ))
+1
1

OrderByDescending?;)

+2

Source: https://habr.com/ru/post/1786031/


All Articles