如何使用LINQ获取所有关系记录

时间:2011-11-08 13:33:43

标签: c# linq

这样的表:

id | userid |   contentid
-------------------------
41 |   92   |     1187
42 |   92   |     1189
43 |   92   |     1190
44 |   92   |     1193
45 |   92   |     1200
46 |   92   |     1201
47 |   92   |     1202
48 |   104  |     1200
49 |   104  |     1201
50 |   104  |     1202
51 |   103  |     1200
52 |   103  |     1201
53 |   103  |     1202

我试图用1202(例如)获取所有相关的内容ID。

  1. 我会将已添加此内容的所有用户分组。
  2. 根据除1202之外的内容ID对记录进行分组后, 组的数量必须按排序。
  3. 很快我想得到以下列表:

    1201 - count: 3
    1200 - count: 3
    1187 - count: 1
    1189 - count: 1
    1190 - count: 1
    1193 - count: 1
    

    我尝试了类似以下的查询,但我还需要做更多其他事情。

    (from x in IRepository<ContentRelation>().Query().ToList()
        where x.Content.Id == content.Id
        group x by x.GUser.Id into c
        select new
        {
          a = c.Key,
          b = (from d in IRepository<ContentRelation>().Query()
               where d.GUser.Id == c.Key && d.Content.Id != content.Id
               select d)
        })
    

    编辑: 我得到了我想要的以下查询,但我不确定这是正确的方式:

    var q = DependencyResolver.Current.GetService<IRepository<ContentRelation>>().Query();
    
    List<int> gh = new List<int>();
    
    foreach (var item in q.Where(x => x.Content.Id == content.Id).GroupBy(x => x.GUser.Id).Select(x => x.Key))
    {
        foreach (var a in q.Where(x => x.GUser.Id == item && x.Content.Id != content.Id).ToList())
        {
            gh.Add(a.Content.Id);
        }
    }
    
    foreach (var hhj in gh.GroupBy(x => x).OrderByDescending(x => x.Count()))
    {
        Response.Write(hhj.Key + "-" + hhj.Count()+ "<br />");
    }
    

2 个答案:

答案 0 :(得分:1)

有了你想要的东西(理论上:) :)

IRepository<ContentRelation>().Query().GroupBy(x => x.Content.Id).Select(x => new Tuple<int, int>(x.Key, x.Count())).OrderBy(x => x.First)

答案 1 :(得分:0)

var result = IRepository<ContentRelation>().Query()
                                           .GroupBy(p => p.contentid)
                                           .Select(p => new
                                           {
                                               contentid=p.Key,
                                               counter=p.Count()
                                           });