与朋友的朋友一起实施Discover页面

时间:2014-02-21 16:40:58

标签: c# asp.net linq entity-framework

我有两张桌子 - 用户和关注。下表定义了两个用户,即跟随的用户和所遵循的用户。想想像Twitter一样的想法。

我想做一个推荐的人物页面。这将建议追随者的追随者按其感知的相关性顺序。

所以如果我有人A。

他跟随B和C人员

如果人B和C都跟随人D,而人B跟随人E.人D应该比人E具有更高的相关性,等等。

有人可以帮我构建一个能够以最快的方式执行此操作的查询。考虑到有很多粉丝的人的潜力。

最终,我想要一个页面说 - 看看这些人:约翰跟随着你跟随的4个人。

我的表格样本

public class User 
{
    public long UserId { get; set; }

    public string Name { get; set; }
}

public class Follow 
{
    public long FollowId { get; set; }

    public User Follower { get; set; }
    public User Following { get; set; }
}

编辑 - 基于Patrick Mcdonalds回答的当前查询

var query = from follow in db.Follows
            where follow.WhoIsFollowing == mee
            let friend = follow.WhoTheyAreFollowing
            from friendOfFriend in db.Follows
            where friendOfFriend.WhoIsFollowing == friend
            group friendOfFriend by friendOfFriend.WhoTheyAreFollowing into g
            where g.Key != mee
            select new { UserId = g.Key, Count = g.Count() };

3 个答案:

答案 0 :(得分:1)

您可以从以下内容开始:

List<Follow> followers = new List<Follow>();

var query = from follow in followers
            where follow.Follower.UserId == 1
            let friend = follow.Following
            from friendOfFriend in followers
            where friendOfFriend.Follower.UserId == friend.UserId
            group friendOfFriend by friendOfFriend.Following.UserId into g
            select new { UserId = g.Key, Count = g.Count() };

var suggestionList = query.OrderByDescending(f => f.Count).ToList();

然后你应该过滤掉你已经关注的用户,也可以过滤自己。 (如果你关注的每个人都跟着你回来,你会出现在建议的顶部)

修改

尝试使用以下内容过滤掉自己和关注者:

int me = 1;

var friends = from follow in followers
              where follow.Follower.UserId == me
              select follow.Following.UserId;

var query = from friend in friends
            from friendOfFriend in followers
            where friendOfFriend.Following.UserId != me
            where !friends.Contains(friendOfFriend.Following.UserId)
            where friendOfFriend.Follower.UserId == friend
            group friendOfFriend by friendOfFriend.Following.UserId into g
            select new { UserId = g.Key, Count = g.Count() };

var suggestionList = query.OrderByDescending(f => f.Count).ToList();

答案 1 :(得分:0)

根据您的存储机制,您无需使用“关注”作为中间人。

考虑这个结构:

public class User 
{
    public long UserId { get; set; }
    public string Name { get; set; }
    public List<User> Following { get; set;}
}

现在,您可以轻松检索此人关注的对象。

假设您有一个List<User> userList并且想要搜索它们以查找谁在关注用户ID

var user5 = userList.Where(x => x.UserID == 5).FirstOrDefault();
var usersFollowingUserID5 = userList.Where(x => x.Following.Contains(user5));

答案 2 :(得分:0)

为了与您当前的结构保持一致,您可以这样做:

var john = userList.Where(x=> x.Name == "John").FirstOrDefault();
var peopleFollowingJohn = followingList.Where(x => x.Following ==  john);
var peopleJohnIsFollowing = followingList.Where(x => x.Follower ==  john);