按ID分组并使用Linq显示前1名

时间:2014-09-25 20:50:33

标签: c# entity-framework linq-to-entities

寻找关于使用实体框架和linq进行分组的一些建议。

所以我有一张桌子" tbl_ChatLog"包含userID和sendToUserID等...并且使用此数据我试图显示" Top 1"来自每个" SendToUserID"

所以在我的UI中它看起来像是这样:

  • 1001(包含多个但显示前1个)
  • 1003(包含多个但显示前1个)
  • 1008(包含多个但显示前1个)
  • 1009(包含多个但显示前1个)

我的代码开头如下:

public static List<Chat> getChatMessage() 
        {
            var entities = new FreeEntities();
            //My ID
            Business.User user = Business.User.getUserBySecurityToken();

             List<Chat> chatMessages = 
             (
                from cm in entities.tbl_ChatLog 
                where cm.UserID == user.uid 
                select new Chat 
                { 
                   uid = (int)cm.UserID, 
                   sendToUserID = (int)cm.SendToUserID, 
                   message = cm.Message, dateAdded = (DateTime)cm.DateAdded 
                }
             ).OrderByDescending(x => x.dateAdded).ToList();
            return chatMessages;
        }

希望你能帮我解决这个问题。分组似乎总是抛弃我。

非常感谢,

特里

2 个答案:

答案 0 :(得分:0)

您可以使用groupby

List<Chat> chatMessages =

(from cm in entities.tbl_ChatLog 

where cm.UserID == user.uid 

orderby cm.DateAdded descending

group cm by cm.sendToUserID into grp

select new Chat
{ 

uid = grp.FirstOrDefault().UserID,

sendToUserID = grp.Key, 

message = grp.FirstOrDefault().Message,

dateAdded = grp.FirstOrDefault().DateAdded

}).ToList()

这将为您提供按sendToUserID分组的表格数据列表,以及包含sendToUserID在内的每个属性的每个组的第一个条目。

答案 1 :(得分:0)

最初的问题是尝试从每个唯一的“SendToUserId”中选择第一条消息并按UserId进行分组,然后选择进入DTO是一场噩梦,但我设法得到一个简单的解决方法。代码如下:

getFirstChatMessage() 
    {
        var entities = new FreeEntities();
        //User ID
        Business.User user = Business.User.getUserBySecurityToken();

        // Create new list of Chat
        List<Chat> chatList = new List<Chat>();

          var res = from c in entities.tbl_ChatLog
          where c.UserID == user.uid
          group c by c.UserID
          into groups
          select groups.OrderByDescending(p => p.DateAdded).FirstOrDefault();

        foreach (var r in res) 
        {
          chatList.Add(new Chat() 
          {
           uid = (int)r.UserID, 
           sendToUserID = (int)r.SendToUserID,
           message = (from m in entities.tbl_ChatLog where m.UserID == (int)r.SendToUserID 
           orderby r.DateAdded descending select m.Message).FirstOrDefault(),
           dateAdded = (DateTime)r.DateAdded, 
           fullName = (from b in entities.tbl_Bio where b.UserID == (int)r.SendToUserID 
           select b.FirstName + " " +      b.SurName).FirstOrDefault() 
          });
        }
        return chatList;
    }