tags:

views:

80

answers:

2

I have a question of how to sort an anonymous type.

Using Linq2SQL I have the following query, which returns a list of submissions:

var submissions = EventSubmissions
    .Where(s => s.EventId.Equals(eventId));

Consider the following interface (somewhat simplyfied):

public interface IQuerySorter
{
    IOrderedQueryable Sort(IQueryable query);
    IOrderedQueryable<T> Sort<T, U>(IQueryable<T> query, Expression<Func<T,U>> selector);
    ...
}

Using this interface allows me to implement a number of 'sorters', e.g. on Date, Rating or whether or not a submission has been nominated (for voting).

sortedQuery = sorter.Sort(submissions)

So far so good. A submission can be made "votable". I get the number of votes a nominated submission may have using the following query:

var withVoteCount = submissions
    .Select(s => new {NumberOfVotes = s.Votes.Count(), Submission = s});

I would like to sort this new query by NumberOfVotes using my "general" sorter class, but run into the problem that the anonymous type/member does not seem to live outside the repository-method, hence I am unable to sort on it.

Any input would be greatly appreciated.

A: 

Nice trick for sorting collection of anonymous objects

KMan
Thanks for the input
strobaek
A: 

I would recommend creating a view or stored procedure using Group By and Count to get the same results as:

var withVoteCount = submissions
    .Select(s => new {NumberOfVotes = s.Votes.Count(), Submission = s});

By using SQL you can tell it to order by Count of votes. Something like this (rough example):

select submissions.ID, submissions.Title, count(votes.ID) as NumberOfVotes 
from submissions inner join votes on submissions.id = votes.submissionid
group by submissions.ID, submissions.Title
order by NumberOfVotes desc

After creating the sql view or stored procedure in your SQL server db, you can just drop it in the designer in Visual Studio and use it as regular class or function.

Juan Tarquino
Thanks, Juan. Something to consider.
strobaek