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

LINQ to SQL, using subquery with IN operator

我是 LINQ to SQL 的初学者。我正在尝试在 LINQ 中使用带有 SQL IN 运算符的子查询。 我正在尝试将查询 friends_Afriends_B 作为子查询与 SQL IN 运算符集成帖子 查询:

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

我不关心是内嵌子查询还是使用变量。

问题是:
如何将查询 friends_Afriends_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();
}

你能试试这个吗

 .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 }));

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

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 
     };