使用LINQ查询获取计数和不同项目?

问题描述

| 我们有下面的sql表:
Tag
----------------------------------------
ID  |   tagName     |   UserID
----------------------------------------
01  |   c++         |   03
02  |   c#          |   03
03  |   asp.net     |   04
04  |   programming |   05
05  |   vb          |   07
06  |   PHP         |   07
07  |   java        |   12
08  |   class       |   12

Tagrelation
----------------------------------------
ID  |   tagID   |   topicID
----------------------------------------
01  |   01      |   22
02  |   02      |   22
03  |   08      |   22
04  |   06      |   12
05  |   02      |   12
06  |   04      |   104
07  |   02      |   104
08  |   01      |   104
09  |   02      |   17
10  |   05      |   17
现在我想为每个使用LINQ查询用户
Tagrelation
表中重复每个标签次数。 我使用了以下查询,但无法编译,但存在一些错误
DataClassesDataContext dbc = new DataClassesDataContext();
var query = from q in dbc.Tags
            where q.UserID == this.UserID
            from c in dbc.Tagrelations
            where c.tagID == q.id
            select new
            {
                tagName = q.name.distinct(),repeatNumber = c.Count()
            };
我该怎么做?谢谢。 编辑:实际上我期望以下结果:
result (if UserID==3)

-------------------------
tagName |   repeatNumber
-------------------------
c++     |   02
c#      |   01
    

解决方法

var q = ...
        group r by r.TagName into g;
        select new
        {
            TagName = g.Key,Count = g.Count()
        };

foreach (var i in q)
{
    string tagName = i.TagName;
    int count = i.Count;    
}    
    ,
from t in dbc.Tags
where t.UserID == this.UserID
join r in dbc.TagRelations on t.id equals r.tagID
group r by t into g
select new
{
    tagName = g.Key.name,repeatNumber = g.Count()
};