如何在 C# lambda 中从 group by 中获取 X 元素

How to take X elements from a group by in C# lambda

我想从 groupby 中取出最后 4 个元素,然后将其添加到列表中。我使用 MySQL 作为数据库和 asp MVC5。我试过这个:

List<Payments> payments= db.Payments
    .Where(e => e.Account.Active==true)
    .GroupBy(e => e.IdAccount)
    .Select(e => e.OrderBy(x => x.PaidDate).Take(4))
    .SelectMany(e => e).ToList();

我收到以下错误:

Unknown column 'Join2.IdAccount' in 'where clause'

这是付款 class:

public partial class Payment
{
    public int Id { get; set; }

    [ForeignKey("Account")]
    [DisplayName("ID Account")]
    public int IdAccount { get; set; }

    [ForeignKey("Client")]
    [DisplayName("ID Client")]
    public int IdClient { get; set; }

    public Nullable<decimal> Amount { get; set; }

    [DisplayName("Paid date")]
    public System.DateTime PaidDate { get; set; }


    public virtual Account Account { get; set; }
    public virtual Client Client { get; set; }
}

可能是 MySQL 提供者(SQL 表达式创建者)错误。但是,你试过这种方式吗?

List<Payments> payments = db.Payments
    .Where(e => e.Account.Active == true)
    .GroupBy(e => e.IdAccount)
    .Select(e => e.OrderBy(x => x.PaidDate))
    .Take(4)
    .SelectMany(e => e).ToList();

如果这对您没有帮助,您始终可以通过以下方式将所有查询传递给代码:

List<Payments> payments = db.Payments
    .Where(e => e.Account.Active == true)
    .GroupBy(e => e.IdAccount)
    .ToList() // From here all calculations will be on web server, not in SQL. So sql query will be simlier
    .Select(e => e.OrderBy(x => x.PaidDate))
    .Take(4)
    .SelectMany(e => e).ToList();

但是,会影响性能。