Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq query to select top 10 entries with most comments from the table

I have two tables "POSTS" and "COMMENTS". One post can have many comments and I want to be able to select the top 10 posts with highest number of comments. The post_id is a FK in the comments table. I am using Linq to SQL. Please advise me on how to do this . Thanks in advance.

EDIT

var top = (from q in db.question_tables
                   from a in db.answer_tables
                   where q.QUEST_ID.Equals(a.ANS_QUEST_ID)
                   orderby q.QUEST_TEXT.Count() descending
                   select new
                   {
                       QUEST_TEXT = q.QUEST_TEXT


                   }).Take(10);

this is how my linq query looks like now , its giving an error "Sequence operators not supported for type 'System.String'. " . :/

like image 924
Muaado Avatar asked Jan 02 '12 15:01

Muaado


People also ask

Is LINQ faster than for loop?

LINQ syntax is typically less efficient than a foreach loop. It's good to be aware of any performance tradeoff that might occur when you use LINQ to improve the readability of your code.


1 Answers

That error message is because you are calling .Count() on a string property (QUEST_TEXT). That compiles because strings are enumerable. However, Linq-to-SQL doesn't understand this.

If you have the relationship between the two tables mapped in your DBML file, then you can use it in your expression:

var top = (from q in db.question_tables
           orderby q.answers.Count() descending
           select q).Take(10);

However the code you posted doesn't quite match the description you gave. You mention comments, but the code talks about answers.

like image 141
Drew Noakes Avatar answered Oct 21 '22 23:10

Drew Noakes