在LINQ中获取每个分组项的顶部(X)

时间:2013-06-14 16:19:39

标签: c# linq nhibernate

我正在尝试为列中的每个唯一项目选择Top(X)recors。

示例:

Inspections
InspectionId | RestaurauntName | InspectionDate
------------------------------------------------
1               Mom&Pop           10/10/12
2               SandwichesPlace   10/10/12
3               Mom&Pop           10/10/11
4               SandwichesPlace   10/10/11
5               Mom&Pop           10/10/10
6               SandwichesPlace   10/10/10
7               BurgerPlace       10/10/11
8               BurgerPlace       10/10/09
9               BurgerPlace       10/10/08

如果我传递'2'的值作为参数,我想要返回记录1,2,3,4,7,8。

在这个示例代码段中,我试图为每个'restaurantName'记录一些记录。

    public IQueryable<Inspections> 
    GetLatestInspectionDatesForAllRestaurants(int numRecords) {

    IQueryable<Inspections> inspections= _session.Query<Inspections>()
                            .GroupBy(r=> r.RestaurauntName)
                            .SelectMany(g => g
                                            .OrderBy(r => r.InspectionDate)
                                            .Take(numRecords));

            return inspections;
     }

不幸的是我收到了这个错误。

      Query Source could not be identified:
      ItemName = g, ItemType = System.Linq.IGrouping`2

此时在代码中触发异常

  var inspections = _inspectionRepository.GetLatestInspectionDatesForAllRestaurants(2).ToList(); 

我错过了什么?

修改

运行测试后,我确认查询在LINQ-To-Objects中运行良好。是否有可能NHibernate.Linq在这个领域仍然不完整?我做了一个稍微不同的查询(下面)并得到了一个未实现的异常。

       .GroupBy(r=> r.RestaurauntName)
                            .Select(g => g.First()).Take(5)

如果我从最后删除Take(5),我得到以下内容(提醒这是一个样本,我的PK在我的实际案例中是Id)。

  {"Column '.Id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause."}

我是否需要学习使用创建标准?

2 个答案:

答案 0 :(得分:1)

嗯,我得到了我需要生成的SQL,它需要一些研究和诸如此类的东西。我确信我的原始问题与LINQ和NHibernate有关,尽管Robert发布​​的最后一个查询在技术上是正确的解决方法。

这将生成一个SQL脚本,因为IQueryable的性质在必要时不会枚举。 SQL本身生成“Where Exists”子句。

public IQueryable<Inspections> 
GetLatestInspectionDatesForAllRestaurants(int numRecords)
{
     var subQuery =  _session.Query<Inspections>()
     .OrderByDescending(x => x.InspectionDate);

     var inspections = _session.Query<Inspections>()
                        .Where(x => subQuery.Where(y => y.InspectionDate == 
                               x.InspectionDate).Take(numRecords).Contains(x))
                        .OrderBy(x => x.WellDataId);
    return inspections;
}

在那里,希望它最终帮助其他人。

答案 1 :(得分:0)

public class Inspections{
    public int InspectionId {get;set;}
    public string RestaurantName {get;set;}
    public DateTime InspectionDate {get;set;}
}
void Main()
{
    var result=GetLatestInspectionDatesForAllRestaurants(2);
    result.Dump();
}
public IQueryable<Inspections> 
    GetLatestInspectionDatesForAllRestaurants(int numRecords) {
        var i = new[]{
        new Inspections{InspectionId=1,RestaurantName="Mom&Pop",InspectionDate=DateTime.Parse("10/10/12")},
        new Inspections{InspectionId=2,RestaurantName="SandwichesPlace",InspectionDate=DateTime.Parse("10/10/12")},
        new Inspections{InspectionId=3,RestaurantName="Mom&Pop",InspectionDate=DateTime.Parse("10/10/11")},
        new Inspections{InspectionId=4,RestaurantName="SandwichesPlace",InspectionDate=DateTime.Parse("10/10/11")},
        new Inspections{InspectionId=5,RestaurantName="Mom&Pop",InspectionDate=DateTime.Parse("10/10/10")},
        new Inspections{InspectionId=6,RestaurantName="SandwichesPlace",InspectionDate=DateTime.Parse("10/10/10")},
        new Inspections{InspectionId=7,RestaurantName="BurgerPlace",InspectionDate=DateTime.Parse("10/10/11")},
        new Inspections{InspectionId=8,RestaurantName="BurgerPlace",InspectionDate=DateTime.Parse("10/10/09")},
        new Inspections{InspectionId=9,RestaurantName="BurgerPlace",InspectionDate=DateTime.Parse("10/10/08")}
    };
    var result=i.GroupBy(g=>g.RestaurantName).SelectMany(g=>g.OrderByDescending(d=>d.InspectionDate).Take(2));
    return result.AsQueryable();
    }

这样运行得很好,所以我假设你的原始查询的生命周期有问题。请尝试以下方法:

public IQueryable<Inspections> 
  GetLatestInspectionDatesForAllRestaurants(int numRecords)
{

  IQueryable<Inspections> inspections= _session.Query<Inspections>()
                        .GroupBy(r=> r.RestaurauntName)
                        .SelectMany(g => g
                                        .OrderByDescending(r => r.InspectionDate)
                                        .Take(numRecords));

  return inspections.ToList().AsQueryable();
}

这是第三种选择,表现不佳,但应从等式中消除NHibernate:

public IQueryable<Inspections> 
  GetLatestInspectionDatesForAllRestaurants(int numRecords)
{

  IQueryable<Inspections> inspections= _session.Query<Inspections>().ToList()
                        .GroupBy(r=> r.RestaurauntName)
                        .SelectMany(g => g
                                        .OrderByDescending(r => r.InspectionDate)
                                        .Take(numRecords));

  return inspections.ToList().AsQueryable();
}