【问题标题】:How to get all of relational records using LINQ如何使用 LINQ 获取所有关系记录
【发布时间】:2011-11-08 13:33:43
【问题描述】:

这样的表格:

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 对记录进行分组后, 必须排序的组数。

很快我想得到以下列表:

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 />");
}

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    这样你就得到了你想要的(理论上:))

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

    【讨论】:

      【解决方案2】:
      var result = IRepository<ContentRelation>().Query()
                                                 .GroupBy(p => p.contentid)
                                                 .Select(p => new
                                                 {
                                                     contentid=p.Key,
                                                     counter=p.Count()
                                                 });
      

      【讨论】:

        猜你喜欢
        • 2014-10-21
        • 2016-03-25
        • 2015-06-18
        • 2019-06-20
        • 2019-06-12
        • 2021-05-14
        • 1970-01-01
        • 1970-01-01
        • 2021-02-27
        相关资源
        最近更新 更多