如何在linq lambda中使用带有2个语句的sql IN语句

时间:2013-03-19 15:40:41

标签: c# linq

我的陈述是

Contents.
    Select(x=> new 
        {
            ContentUsers = x.ContentUsers.
                Where(t=>t.UserId==2).
                Select(t=>t.ContentId)
        }).
    Where(y=>y.ContentUsers.Any())

它给了我一些我想用它的ID我的另一个陈述。

enter image description here

Contents.Where(x=>x.Id == 633,634,635)

我如何合并它们?

1 个答案:

答案 0 :(得分:1)

您缺少的是Contains功能。在单个查询表达式中表达它可能更简单。如果我将您的代码翻译成单个查询表达式,我看起来像这样:

var content =
    from c in Contents
    let contentUsers = 
        from x in Contents
        select new
        {
            ContentUsers = 
                from t in x.ContentUsers
                where t.UserId == 2
                select t.ContentId
        }
    where contentUsers.Any(cu => cu.ContentUsers.Contains(c.Id))
    select c;

但是,看起来您只想获得与Content集合中给定UserID相关联的ContentUsers条记录。这很容易。

var content =
    from c in Contents
    where c.ContentUsers.Any(t => t.UserId == 2)
    select c;

或者如果您愿意

var content = Contents.Where(c => c.ContentUsers.Any(t => t.UserId == 2));