我如何在我的所有邮件上进行分组

时间:2016-03-02 21:12:05

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

我正在尝试获取每个用户的所有邮件数

msg 1 = SenderId =1  , ReciverId =2 
msg 2 = SenderId =2  , ReciverId =1
msg 3 = SenderId =1  , ReciverId =2
  

我认为在同一个用户中与同一个用户进行1次聊天,因此在我的示例中   查询需要重新生成我有一条消息

对此的查询是什么?  我在底部写了一个查询,告诉我想要什么 但是非法,我是怎么写的?

public class UserMessages
{
    public long Id { get; set; }
    public long SenderId { get; set; }
    public long ReciverId { get; set; }
    public string Text { get; set; }
    public DateTime? DateTime { get; set; }
    public bool FastMessage { get; set; }
    public bool SenderDelete { get; set; }
    public bool ReciverDelete { get; set; }
    public bool ReciverRead { get; set; }
}

        var UserMessages = db.UserMessages
                             .Where(x => (x.SenderId == id && x.SenderDelete == false) ||
                                         (x.ReciverId == x.Id && x.ReciverDelete == false))
                             .GroupBy(x => new { x.ReciverId, x.SenderId })
                             .GroupBy((y, w) => y.Key.SenderId == w.Key.ReciverId
                                                && y.Key.ReciverId == w.Key.SenderId)
                             .Count();

2 个答案:

答案 0 :(得分:0)

我的看法是这样的:

var result = db.UserMessages
               .Where(x => x.SenderId == id || x.ReceiverId == id)
               .Select(x => x.ReceiverId == id ? x.SenderId : x.ReceiverId)
               .Distinct()
               .Count();

答案 1 :(得分:0)

var id = 1; // the ID of the person to count chat partners for

var chatPartnerCount = db.UserMessages
    .Where(x => x.SenderId == id && !x.SenderDelete || x.ReceiverId == id && !x.ReceiverDelete)
    .GroupBy(x => x.SenderId == id ? x.ReceiverId : x.SenderId) // group by the chat partner
    .Count(); // count the number of unique chat partners