C# 如何使用LINQ获取所有关系记录
如下表所示:C# 如何使用LINQ获取所有关系记录,c#,linq,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 |
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(例如)
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)
})
(来自IRepository().Query().ToList()中的x)
其中x.Content.Id==Content.Id
由x.GUser.Id将x分组为c
选择新的
{
a=c.键,
b=(来自IRepository().Query()中的d)
其中d.GUser.Id==c.Key&&d.Content.Id!=Content.Id
选择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 />");
}
var q=DependencyResolver.Current.GetService().Query();
List gh=新列表();
foreach(q.Where中的变量项(x=>x.Content.Id==Content.Id).GroupBy(x=>x.GUser.Id).选择(x=>x.Key))
{
foreach(q.Where(x=>x.GUser.Id==item&&x.Content.Id!=Content.Id).ToList()中的变量a)
{
gh.Add(a.Content.Id);
}
}
foreach(gh.GroupBy(x=>x.OrderByDescending(x=>x.Count())中的var hhj)
{
Write(hhj.Key+“-”+hhj.Count()+“
”);
}
这样你就得到了你想要的(理论上:)
IRepository().Query().GroupBy(x=>x.Content.Id)。选择(x=>newtuple(x.Key,x.Count())。OrderBy(x=>x.First)
var result=IRepository().Query()
.GroupBy(p=>p.contentid)
.选择(p=>new
{
contentid=p.Key,
计数器=p.计数()
});
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()
});