簡體   English   中英

如何使用LINQ獲取所有關系記錄

[英]How to get all of relational records using 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(eg)獲取所有相關的內容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 />");
}

這樣,您就得到了想要的(理論上:))

IRepository<ContentRelation>().Query().GroupBy(x => x.Content.Id).Select(x => new Tuple<int, int>(x.Key, x.Count())).OrderBy(x => x.First)
var result = IRepository<ContentRelation>().Query()
                                           .GroupBy(p => p.contentid)
                                           .Select(p => new
                                           {
                                               contentid=p.Key,
                                               counter=p.Count()
                                           });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM