LINQ to SQL,使用带有IN运算符的子查询

时间:2015-04-12 20:53:25

标签: c# linq visual-studio linq-to-entities

我是LINQ to SQL的初学者。我试图在LINQ中使用带有SQL IN运算符的子查询。 我正在尝试将查询 friends_A friends_B 作为子查询与帖子查询中的SQL IN运算符进行整合:

where p.UserName IN (friends_A)
where p.UserName IN (friends_B)

我不在乎是否将子查询内联或使用变量进行整合。

问题是:
如何将查询 friends_A friends_B (内联或使用变量)与SQL IN运算符集成?

额外问题:如何从联盟订购整体结果(在var posts中): orderby p.DateAndTime

using (FacebookDataEntities entities = new FacebookDataEntities())
{

    var friends_A = from f in entities.Friends
                   where f.Friend_A != User.Identity.Name
                   && f.Friend_B == User.Identity.Name
                   select f.Friend_A;

    var friends_B = from f in entities.Friends
                   where f.Friend_A == User.Identity.Name
                   && f.Friend_B != User.Identity.Name
                   select f.Friend_B;

   var posts = ((from p in entities.Posts
     where p.UserName.ToLower() == User.Identity.Name
     select new { p.UserName, p.DateAndTime, p.PostText })

     .Union(from p in entities.Posts
            where p.UserName IN (friends_A)
            select new { p.UserName, p.DateAndTime, p.PostText })

     .Union(from p in entities.Posts
            where p.UserName IN (friends_B)
            select new { p.UserName, p.DateAndTime, p.PostText }));

   ListViewPosts.DataSource = posts.ToList();
   ListViewPosts.DataBind();
}

2 个答案:

答案 0 :(得分:1)

查看您的代码我认为这就是您所需要的。通过这种方式,你也可以避免工会。

var friends_A = from f in entities.Friends
                   where f.Friend_A != User.Identity.Name
                   && f.Friend_B == User.Identity.Name
                   select f.Friend_A;

var friends_B = from f in entities.Friends
                   where f.Friend_A == User.Identity.Name
                   && f.Friend_B != User.Identity.Name
                   select f.Friend_B;

var posts = 
     from p in entities.Posts
     let userName = p.UserName.ToLower()
     where 
        userName == User.Identity.Name ||
        friends_A.Concat(friends_B).Contains(userName)
     orderby 
        p.DateAndTime
     select new 
     { 
        p.UserName, 
        p.DateAndTime, 
        p.PostText 
     };

答案 1 :(得分:0)

你能试试吗?

 .Union(from p in entities.Posts
        where friends_A.Any(f => f.Name == p.UserName)
        select new { p.UserName, p.DateAndTime, p.PostText })

 .Union(from p in entities.Posts
        where friends_B.Any(f => f.Name == p.UserName)
        select new { p.UserName, p.DateAndTime, p.PostText }));