开发者

C# Groupby Distinct

I have a database table 开发者_JS百科(called Info) that stores [Data], [fkID], [UserID], 1675055493. [Data] is actually multiple columns, but it doesn't really matter.

Essentially a user can go and input data into a form, and the form inserts a new row into Info.

What I want to be able to do is select the most recent [Data] item from each [UserID] for a specific [fkID]. This can be done in LINQ, I just haven't figured it out. Here is what I have so far:

var q = (from i in db.Info
        where i.fkID == @paramID
        orderby Timestamp descending
        groupby new {i.UserID})
        .Distinct()

This obviously doesn't work. It returns the correct UserID but not the [Data] part that I actually want.

In words, here is what I want to do:

For each entry in Info with a certain fkID, I want to select the most recent row from each User.

I'd like to know how to do this in LINQ.


You need to select the first row in each group, like this:

var q = from i in db.Info
        where i.fkID == @paramID
        group i by i.UserID into g
        select new { 
            UserID = g.Key, 
            Recent = g.OrderByDescending(i => i.Timestamp).First() 
        };


You should use .First() instead of .Distinct()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜