2014-02-21 37 views
0

我有兩張表 - User和Follows。下表定義了兩個用戶,即關注的用戶和關注的用戶。想想接下來的Twitter這樣的想法。與朋友的朋友一起實現發現頁面

我想做一個建議的人物頁面。這將建議追隨者按照他們的感知相關性。

所以,如果我有個人A.

他跟隨人B和C

如果人B和C都遵循人·d,和某乙遵循人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; } 
} 

編輯 - 當前查詢基於帕特里克麥當勞回答

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

回答

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(); 

然後你應該p可以過濾掉你已經關注的用戶,還有你自己。 (如果大家你跟着跟着你回來,你將出現在建議頂部)

編輯

嘗試類似以下篩選出你和你的追隨者:

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(); 
+0

驚人。到底是什麼我以後。我可以問一個簡短的問題嗎?我編輯了這篇文章,根據你的文章添加我使用過的文章,並且效果很好。但是有什麼機會可以幫助刪除登錄用戶所關注的人?目前,我運行該查詢,它隨用戶(登錄用戶)隨之而來,因此我將它們過濾掉 – MichaelMcCabe

0

根據您的存儲機制,你不需要使用「關注」爲中介。

考慮這樣的結構:

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

現在您可以輕鬆檢索人以下誰。

比方說你有一個List<User> userList,並且希望通過他們搜索找到誰在關注用戶ID 5

var user5 = userList.Where(x => x.UserID == 5).FirstOrDefault(); 
var usersFollowingUserID5 = userList.Where(x => x.Following.Contains(user5)); 
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);