0

I want to retrieve multiple values from single table based on multiple conditions using only one LINQ query. my table looks like:

ArticleId (int)
ArticleName (string)
CreatedDate (datetime)
ArticleType (string)
Views (int)

I want to retrieve:

  1. top 5 recently created articles,
  2. top 5 articles with maximum views,
  3. top 5 articles with ArticleType = "News"

using only one LINQ query. i am new to learning these things, so i dont know if this is even possible. pardon me if this is a stupid question. and if any body could please answer in method syntax in LINQ. any help is appriciated.

1 Answers1

0

I'm going to be answering in method syntax, and in multiple queries (since a single wouldn't be readable and I dont see why you would want one)

top 5 recently created articles articles.OrderByDescending(a => a.CreatedDate).Take(5);

top 5 articles with maximum views articles.OrderByDescending(a => a.Views).Take(5);

top 5 articles with ArticleType = "News" Don't know how to define top here, but you can fill in the blanks:

articles. Where(a => a.ArticleType == "News").OrderBy(...).Take(5);

eavidan
  • 5,324
  • 1
  • 13
  • 16
  • thank you for reply. the reason that i want to do the above thing in one single query is so that there is only single trip to database to fetch all this information. i was looking to do this in single query. thanks anyways for the help. – Tajveer Singh Nijjar Sep 25 '16 at 21:18
  • It's a bit hard, since you order the entire collection in different ways. The only way to do so is read the entire collection into the program memory and do what I wrote above, but that would generally be a bad idea – eavidan Sep 25 '16 at 21:20
  • yes u r right @eavidan. i also thought of the same approach in the beginning. but then the query would become really heavy when the number of records is in 1000s. thank you. – Tajveer Singh Nijjar Sep 25 '16 at 21:22