sql server到linq group by

时间:2013-08-22 01:17:55

标签: c# sql sql-server linq

我正在学习linq。

我在sql server中:

create table Something(id int, num int)

insert into Something(id, num) values(1, 10);
insert into Something(id, num) values(1, 10);
insert into Something(id, num) values(2, 7);
insert into Something(id, num) values(2, 7);
insert into Something(id, num) values(2, 7);
insert into Something(id, num) values(3, 5);
insert into Something(id, num) values(3, 5);
insert into Something(id, num) values(3, 5);
insert into Something(id, num) values(3, 5);
insert into Something(id, num) values(3, 5);
insert into Something(id, num) values(3, 5);
insert into Something(id, num) values(4, 5);

select id 
from something
group by id, num
having count(*) < num

结果是:4,2和1

我正在尝试使用linq:

var query =
(from m in lst
group m by new { m.id, m.num } into g
where g.Count() < m.num).ToList();

我想将g.Count()与“num”字段进行比较,但我的代码中有些错误

Thansk的帮助!

1 个答案:

答案 0 :(得分:2)

尝试使用g.key.num代替m.num

var query =
(from m in lst
group m by new { m.id, m.num } into g
where g.Count() < g.key.num).ToList();