如何在Entity Framework Core中按分组而不重复分组?

时间:2018-10-11 17:44:52

标签: mysql entity-framework linq .net-core

我想在Entity Framework核心中执行分组,没有重复的分组。

假设我有两列

Column A     Column B
1            1
2            1
2            1
4            5
5            4

如果对两列实体框架核心执行group by,结果将非常明显。

Column A     Column B
1            1
2            1
4            5
5            4

但是我想执行一个通过A-> B和B-> A两种方式工作的小组,因此结果将是

Column A     Column B
1            1
2            1
5            4

有什么想法如何在Entity Framework Core中做到这一点?

我最初的尝试是使用Union

 var user = _context.Transactions
        .Where(p => !p.IsDeleted && (p.ReceiverUserId == userId) &&
                    (p.SenderUserId != null))
        .Include(p => p.SenderUser)
        .GroupBy(p => p.SenderUserId)
        .Select(p => new TempModel { Id = p.FirstOrDefault().SenderUser.Id, User = p.FirstOrDefault().SenderUser, CreatedDate = p.FirstOrDefault().CreatedDate });

    var user2 = _context.Transactions
        .Where(p => !p.IsDeleted && (p.SenderUserId == userId) &&
                    (p.ReceiverUserId != null))
        .Include(p => p.ReceiverUser)
        .GroupBy(p => p.ReceiverUserId)
        .Select(p => new TempModel { Id = p.FirstOrDefault().ReceiverUser.Id, User = p.FirstOrDefault().ReceiverUser, CreatedDate = p.FirstOrDefault().CreatedDate});

    var finalQuery = user.Union(user2);
    var finalQuery2 = finalQuery.GroupBy(p => p.Id);
    var finalQuery1 = finalQuery2.OrderByDescending(p => p.FirstOrDefault().CreatedDate);


finalQuery.GroupBy(p => p.Id); <- this line gives error

1 个答案:

答案 0 :(得分:0)

您应按降序对这些列进行排序:4-5 => 5-4; 5-4 => 5-4; 5-5 => 5-5,然后group bydistinc,他们:

var answer = db.Table.Select(x => new 
{                 
    ColumnA = x.ColumnA > x.ColumnB ? x.ColumnA : x.ColumnB,
    ColumnB = x.ColumnA > x.ColumnB ? x.ColumnB : x.ColumnA
}).Distinct().ToList();