c# - Sql to Linq 难点——group by, having

标签 c# sql linq group-by having

我在 SQL 中有以下查询,我想将其转换为 LINQ:

select profile_id from t
where child_id in (1, 2 ,3, ...) //this will be a list of integers CHILDREN
group by profile_id
having count(distinct child_id) = 3

我很难将我的 sql 查询中的最后一行写入 linq。以下是我到目前为止的工作:

public IQueryable<ProfileChildRelationship> GetPCRelByCids(List<int> children)
    {
        var query = from pcr in this._entities.ProfileChildRelationships
                    where children.Contains(pcr.pcChildIDF)
                    group pcr by pcr.pcProfileIDF into g
                    ??? having ...?
                    select pcr;

        return query;
    }

我认为这可能的主要问题是许多人将 having sql 语句转换为 where linq 语句,但就我而言,我认为不可能在 group by linq 语句之后编写另一个 where!

更新:

情况:我有很多 child ,每个 child 都有很多不同的个人资料(有些可能相同)。用户将选择一些 child ,我想从中得出他们的共同配置文件。也就是说,如果为每个 child 都找到配置文件 X,那么我会得到它,如果为除了一个 child 之外的每个 child 都找到配置文件 Y,那么它将无效!

最佳答案

听起来你想要一个 where 子句...

var query = from pcr in this._entities.ProfileChildRelationships
            where children.Contains(pcr.pcChildIDF)
            group pcr by pcr.pcProfileIDF into g
            where g.Select(x => x.ChildId).Distinct().Count() == 3
            select g.Key; // This is the profile ID

关于c# - Sql to Linq 难点——group by, having,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10398392/

相关文章:

c# - 在 LINQ 中按时间跨度分组

c# - 带有事件名称的 NetworkStream write()

c# - 如何使用 View 模型

c# - asp.net mvc 4在AuthorizeAttribute中结束请求

SQL 交叉表和数据透视表

mysql - 使用 SQL 聚合多列上的正值

mysql - 插入 SQL 查询时缺少分号

c# - 忽略 Linq.Any 中的大小写,C#

c# - 使用通过 DI 容器注入(inject)的抽象工厂

c# - 查询嵌套集合(父/子)