按关系计数排序的多对多(实体框架,Linq)

时间:2010-10-11 23:16:04

标签: c# entity-framework linq-to-entities

我有这样的表格结构......

alt text

当我将其导入实体框架时,它看起来像这样......

alt text

我需要做的是从LINQ构建一个查询,该查询将返回每个唯一商店的列表,其中填充了喜欢该商店的人员列表。 (很简单,对吧?)

THE CATCH: 我需要将列表过滤到个人的朋友列表,这些朋友列表作为列表传递给linq查询(来自facebook,因此关系不在db中)...

还有一件事: 我需要返回,如果商店是请求数据的人的最爱(uid,如下所示)

好的,另外一件事: 我需要将最喜欢某个项目的朋友排序的列表返回到最低(下面的ui在这方面是错误的)

这是我需要的linq查询的方法签名

public List<Store> GetTopStoresFilteredByFriends
          (int uid, List<int> friends, int size = 10){

}

返回看起来像这样的用户界面......

alt text

2 个答案:

答案 0 :(得分:2)

此查询为您提供了每个唯一商店的列表,其中填充了一个喜欢该商店的人员列表,该列表中的至少一个朋友也喜欢该商店,这些朋友正在通过最多数量的朋友订购比如商店加上一个标志,以显示请求数据的人是否喜欢每个商店:

var query = (from s in ctx.Stores.Include("People")
             from p in s.People
             let n = friends.Sum(f => s.People.Count(item => item.PersonID == f))
             where friends.Any(f => f == p.PersonID)
             select new {
                 TheStore = s,
                 IsFavorite = s.People.Any(ppl => ppl.PersonID == uid),
                 N = n
             })
             .Distinct()
             .OrderByDescending(o => o.N);

答案 1 :(得分:0)

伪代码

var stores = new Dictionary();

//每个商店一个条目,以count = 0

开头

stores.Add(1,0);

stores.Add(2,0);

stores.Add(3,0);

var peopleWithFriends = new Dictionary&lt; int,List&lt;人&gt; &GT; ();

//每个人的一个条目,包含朋友列表
var person0 = new Person(); person0.Id = 0;

var person1 = new Person(); person1.Id = 1;

var person2 = new Person(); person2.Id = 2;

peopleWithFriends.Add(0,new List&lt; Person&gt; {person1,person2}); peopleWithFriends.Add(1,new List&lt; Person&gt; {person0,person2}); peopleWithFriends.Add(2,new List&lt; Person&gt; {person0,person1});

foreach(var store in  peopleWithFriends.Keys.Select(personId =&gt; peopleWithFriends [personId])   .SelectMany(friends =&gt; Enumerable.SelectMany(friends,friend =&gt; friend.Stores))) {  店[store.Id] ++; }

现在您可以按最高计数对商店字典进行排序,并返回结果