2

I have to show the movies which have most wanted to see status. For this I Join two tables 1. MovieInformation and 2. SeentItWantToSeeIt. I calculated most wanted to see movie with this code snippets.

public class RangkedMovieList
{
    public int MovieID { get; set; }
    public int count { get; set; }
}

rankedList = db.SeenItWantToSeeIt.Where(m => m.Status == 1 && m.MovieID != null)
                                 .GroupBy(m => m.MovieID)
                                 .Select(g => new RangkedMovieList 
                                              {  MovieID = g.Key.Value,
                                                 count = g.Count() 
                                              })
                                 .ToList();

AllMovieInfo is Iqueryable with which I joined wanted to see movies.

AllMovieInfo = (from r in rankedList
                join a in AllMovieInfo on r.MovieID equals a.MovieID
                orderby r.count descending
                select a).Distinct().AsQueryable();

This query works fine and orders the result by MovieID but I want to order all movies by their wanted to see count. Though I have written code to orderby r.count descending, Its not working. Please help me out.

4

1 回答 1

1

I'm guessing your second LINQ query is operating at the database level. If so, it's likely that the Distinct call won't honor the previously specified sort order (in fact, if you drop the Distinct call and debug your output, it should appear sorted correctly). Typically for simple queries you can fix this by swapping the order of the sort (i.e., orderby) and Distinct call while keeping the query on the database level, as answered in another post, but your case is a little more complicated since you need to work with rankingList.

In your case you could bring it down to the LINQ to Objects level by adding a ToList() as you did for the first query, or an AsEnumerable(). At that level you wouldn't need to worry about swapping the order of the sort or distinct call. However, you'll likely need to use the overloaded Distinct method that accepts an IEqualityComparer and provide a comparer for AllMovieInfo. Check out the link for an example of how to implement that.

var query = (from r in rankedList
            join a in AllMovieInfo on r.MovieID equals a.MovieID
            select new { Info = a, Rank = r.count })
            .AsEnumerable()
            .OrderByDescending(o => o.Rank);
            .Select(o => o.Info)
            .Distinct(); // will likely need an IEqualityComparer here

// this could be combined with the above query, but I split it for clarity
AllMovieInfo = query.AsQueryable();

You might not need the AsQueryable at that point since it's already on the client at that point, in memory.

于 2013-09-22T01:42:21.170 回答