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 woul开发者_开发知识库d 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.
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.
精彩评论