0

I am working on an application in which I have to store play history of a song in the data table. I have a table named PlayHistory which has four columns.

Id | SoundRecordingId(FK) | UserId(FK) | DateTime

Now i have to implement a query that will return the songs that are in trending phase i.e. being mostly played. I have written the following query in sql server that returns me data somehow closer to what I want.

select  COUNT(*) as High,SoundRecordingId
from PlayHistory
where DateTime >= GETDATE()-30
group by  SoundRecordingId
Having COUNT(*) > 1
order by SoundRecordingId desc

It returned me following data:

High  SoundRecordingId
2       5
2       3

Which means Song with Ids 5 and 3 were played the most number of times i.e.2 How can I implement this through Linq in c#. I have done this so far:

        DateTime d = DateTime.Now;
        var monthBefore = d.AddMonths(-1);
        var list =
            _db.PlayHistories
            .OrderByDescending(x=>x.SoundRecordingId)
            .Where(t => t.DateTime >= monthBefore)
            .GroupBy(x=>x.SoundRecordingId)
            .Take(20)
            .ToList();

It returns me list of whole table with the count of SoundRecording objects but i want just count of the most repeated records. Thanks

3
  • .OrderByDescending(x=>x.SoundRecordingId)... allready is linq. So what else do you want? Nov 20, 2017 at 13:29
  • @HimBromBeere I have edited my question Nov 20, 2017 at 13:31
  • Your issue is that your linq does not perform a count, there is an overload to GroupBy which allows you to do this. See my answer. Nov 20, 2017 at 13:45

4 Answers 4

2

There is an overload of the .GroupBy method which will solve your problem.

DateTime d = DateTime.Now;
    var monthBefore = d.AddMonths(-1);
    var list =
        _db.PlayHistories
        .OrderByDescending(x=>x.SoundRecordingId)
        .Where(t => t.DateTime >= monthBefore)

        .GroupBy(x=>x.SoundRecordingId, (key,values) => new {SoundRecordingID=key, High=values.count()})

        .Take(20)
        .ToList();

I have simply added the result selector to the GroupBy method call here which does the same transformation you have written in your SQL.

The method overload in question is documented here

To go further into your problem, you will probably want to do another OrderByDescending to get your results in popularity order. To match the SQL statement you also have to filter for only counts > 1.

DateTime d = DateTime.Now;
    var monthBefore = d.AddMonths(-1);
    var list =
        _db.PlayHistories
        .Where(t => t.DateTime >= monthBefore)
        .GroupBy(x=>x.SoundRecordingId, (key,values) => new {SoundRecordingID=key, High=values.count()})
        .Where(x=>x.High>1)
        .OrderByDescending(x=>x.High)
        .ToList();
0
2

I like the 'linq' syntax it's similar to SQL

var query = from history in _db.PlayHistories
            where history.DateTime >= monthBefore
            group history by history.SoundRecordingId into historyGroup
            where historyGroup.Count() > 1
            orderby historyGroup.Key
            select new { High = historyGroup.Count(), SoundRecordingId = historyGroup.Key };

var data = query.Take(20).ToList();
2
  • That´s not the "linq-syntax", it´s called the query-syntax , in contrast to the method syntax. Nevertheless this isn´t wnat OP is asking. Nov 20, 2017 at 13:32
  • Thanks @Filip using your solution i was able to get the required result, but its in query synatx, i wanted to use method syntax. Nov 21, 2017 at 4:56
0

You´re allmost done. Just order your list by the count and take the first:

var max =
        _db.PlayHistories
        .OrderByDescending(x=>x.SoundRecordingId)
        .Where(t => t.DateTime >= monthBefore)
        .GroupBy(x=>x.SoundRecordingId)
        .OrderByDescending(x => x.Count())
        .First();

This gives you a single key-value-pair where the Key is your SoundRecordingId and the value is the number of its occurences in your input-list.

EDIT: To get all records with that amount chose this instead:

var grouped =
        _db.PlayHistories
        .OrderByDescending(x => x.SoundRecordingId)
        .Where(t => t.DateTime >= monthBefore)
        .GroupBy(x => x.SoundRecordingId)
        .Select(x => new { Id = x.Key, Count = x.Count() }
        .OrderByDescending(x => x.Count)
        .ToList();
var maxCount = grouped.First().Count;
var result = grouped.Where(x => x.Count == maxCount);
2
  • Shouldn't be the Take after OrderByDescending and ToList() instead of First()?
    – Rabban
    Nov 20, 2017 at 13:39
  • This only gave me a single record. There can be more than one record, like my example. Nov 20, 2017 at 13:40
0

This solves the problem by giving you what you asked for. Your query in LINQ, returning just the play counts.

var list = _db.PlayHistories.Where(x => x.DateTimeProp > (DateTime.Now).AddMonths(-1))
           .OrderByDescending(y => y.SoundRecordingId.Count())
           .ThenBy(z => z.SoundRecordingId)
           .Select(xx => xx.SoundRecordingId).Take(20).ToList();
4
  • The OP is asking for a simple code example. There is no commentary needed. Maybe I should have added "I like LINQ syntax" (no such thing) and you wouldn't have lectured me. Or I could write about the GroupBy overloads even though this query does not need GroupBy for any reason. Nov 20, 2017 at 14:26
  • Why so salty? You know what, I will just not take your little rant personal and hope it helped you relieve some stress..
    – Neuron
    Nov 20, 2017 at 15:24
  • Not every question needs code and not every answer benefits from a caption. "How do I type this single query in a different syntax" is a good example. Read the thread first before calling someone out please. Nov 20, 2017 at 16:09
  • you are right, it was not necessary to provide context for your answer and the comment was probably a little much. I still think that almost every answer (including yours) could benefit frome some short explaination as to what you are doing, as most people asking questions are newcomers or struggeling with a certain topic and most solutions can benefit from some guidance
    – Neuron
    Nov 20, 2017 at 16:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.