【问题标题】:Linq Group selectionLinq 组选择
【发布时间】:2013-11-25 16:46:55
【问题描述】:

我需要过滤这些结果以仅显示每个组的第一行和最后一行。我尝试了几种方法都没有运气。下面是 Linq 查询和结果。

Linq 查询:

var currentAndHistoricalOnly = ViewCustomerGLAndPurchaseRecord
                               .Where(g=>g.CashierDate > new Datetime(2012,10,01)  
                                      &&  g.CashierDate < new DateTime(2012,12,01))
                               .GroupBy(x => x.TransactionId)   
                               .OrderByDescending(d => d.First().CashierDate);

请记住,我试图保持相同的分组,但过滤(删除记录)每个组并且只获取每个组的第一条记录和最后一条记录。

所以而不是:

第 1 组:

  1. 记录 1
  2. 记录 2
  3. 记录 3
  4. 记录 4
  5. 记录 5

第 2 组:

  1. 记录 1
  2. 记录 2
  3. 记录 3
  4. 记录 4

我需要:

第 1 组:

  1. 记录 1
  2. 记录 5

第 2 组:

  1. 记录 1
  2. 记录 4

【问题讨论】:

    标签: c# sql linq


    【解决方案1】:

    可能是这样的:

    var currentAndHistoricalOnly = ViewCustomerGLAndPurchaseRecord
                                     .Where(g=>g.CashierDate > new DateTime(2012,10,01) && g.CashierDate < new DateTime(2012,12,01)) 
                                     .GroupBy(x => x.TransactionId)
                                     .Select(g=> new {
                                         Last = g.OrderByDescending(c=>c.CashierDate).FirstOrDefault(),
                                         First = g.OrderBy(c=>c.CashierDate).FirstOrDefault(),
                                     })
                                     .ToList();
    

    【讨论】:

      【解决方案2】:

      您可以使用lastfirst 方法

      【讨论】:

        【解决方案3】:

        试试这个:

        var list = ViewCustomerGLAndPurchaseRecord
                   .Where(g=>g.CashierDate > new DateTime(2012,10,01) 
                          && g.CashierDate < new DateTime(2012,12,01)) 
                   .GroupBy(x => x.TransactionId)
                   .OrderByDescending(d => d.First().CashierDate)
                   .Select(d =>  
                   {
                        var result = new List<ViewCustomerGLAndPurchaseRecord>();
                        result.Add(d.FirstOrDefault());
                        result.Add(d.LastOrDefault());
                        return result;
                   });
        

        如果您使用的是实体框架,请在选择之前使用 AsEnumerable()

        希望这会有所帮助!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-07-12
          • 1970-01-01
          • 2011-06-19
          相关资源
          最近更新 更多