user2956229
user2956229

Reputation: 51

get most frequently used values with linq

I have items in database, like:

id | item_id | title
1  |    1    |  abc
2  |    3    |  abcd
3  |    1    |  abc
4  |    1    |  abc
5  |    3    |  abcd
6  |    2    |  abcde

What I want is order by most used values
and that most used values must be order by date_created

id | item_id | title
1  |    1    |  abc
3  |    1    |  abc
4  |    1    |  abc
2  |    3    |  abcd
5  |    3    |  abcd
6  |    2    |  abcde

what I've tried so far is

public static ICollection<entry_adders> CallEntries()
{
    using (entry_MainEntities db = new entry_MainEntities())
    {
        var entries = db.entry_adders
            .GroupBy(q => q.item_id)
            .OrderByDescending(gp => gp.Count())
            .Select(g => g.Key).ToList() ;

         return ??
     }
}

But I don't know how to return this to ICollection<entry_adders> and i need this query with linq not lambda.

Upvotes: 0

Views: 1177

Answers (2)

King King
King King

Reputation: 63347

I think you need to use the SelectMany like this:

return db.entry_adders
         .GroupBy(q => q.item_id)
         .OrderByDescending(gp => gp.Count())
         .SelectMany(g=>g).ToList();

Upvotes: 3

aevitas
aevitas

Reputation: 3833

return e.OrderByDescending(d => d.Frequency).ThenByDescending(d => d.CreationTime);

You make the return type of your method IEnumerable<entry_adders> and then you just return entries.

Upvotes: 2

Related Questions