Linq:计数大于值

时间:2014-06-30 10:33:33

标签: linq

我有一个linq查询,它接受日期和端口组合的列表。此查询必须从找到这些组合的表CruiseCalendar返回数据,但仅在计数大于1时才返回。我无法计算出groupby和count语法。 var shipRendezvous是我被困的地方。

        var dateAndPort = (from r in context.CruiseCalendar
                        where r.ShipId == shipId
                        && r.CruiseDayDate >= dateRange.First
                        && r.CruiseDayDate <= dateRange.Last
                        select new DateAndPort
                        {
                            Date = r.CruiseDayDate,
                            PortId = r.PortId
                        });

        var shipRendezvous = (from r in context.CruiseCalendar
                              where (dateAndPort.Any(d => d.Date == r.CruiseDayDate
                              && d.PortId == r.PortId))
                              orderby r.CruiseDayDate // (Added since first posting)
                              select r).ToList();

问候,盖伊

1 个答案:

答案 0 :(得分:3)

如果我理解正确的话,那么你正在为与dateAndPort的任何结果相匹配的每一组进行过滤,然后想要将它自己分组以获得计数。在分组结果中,您只需要那些多次出现的结果集。

var shipRendezvous = (from r in context.CruiseCalendar
                      where (dateAndPort.Any(d => d.Date == r.CruiseDayDate
                      && d.PortId == r.PortId))
                      select r)
                     .GroupBy(x => x.CruiseDayDate) //Groups by every combination
                     .Where(x => x.Count() > 1) //Where Key count is greater 1
                     .ToList();

根据您的评论,您想再次展平列表。为此,请使用SelectMany()

var shipRendezvous = (from r in context.CruiseCalendar
                      where (dateAndPort.Any(d => d.Date == r.CruiseDayDate
                      && d.PortId == r.PortId))
                      select r)
                     .GroupBy(x => x.CruiseDayDate) //Groups by every combination
                     .Where(x => x.Count() > 1) //Where Key count is greater 1
                     .SelectMany(x => x)
                     .ToList();