使用LINQ查询获取Count和Distinct项?

时间:2011-05-01 12:13:26

标签: c# .net linq linq-to-sql

我们有以下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

2 个答案:

答案 0 :(得分:3)

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;    
}    

答案 1 :(得分:2)

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()
};