0

I wrote a LINQ query that it' result similar to this :

var res = from a  in tbl
          group a by {a.StateCode,a.CityCode} into grp
          //where grp.Count() == 1
          select ...

StateCode       CityCode           ......
------------------------------------------
01               001               ......
01               002               ......
02               001               ......
03               001               ......
03               002               ......
03               003               ......

indeed I want to get just 02 001 record because it has one result row in the final result.If I add commented code It returns count of records correspond to each group not count of own group.I know I can do this with two group by but is there a better way to get row that has (for example) one row in the result?

4

2 回答 2

1

您按 StateCodeCityCode 分组,因此每个组只有一个元素。您必须仅按 StateCode 分组并where grp.Count() == 1再次包含。

每个组都包含 StateCode 作为其键和元素的枚举。由于您已经过滤了只有一个元素的组,您可以只返回每个组的第一个:

var res = from a in tbl
          group a by a.StateCode into grp
          where grp.Count() == 1
          select grp.FirstOrDefault();
于 2013-10-26T10:03:35.163 回答
0

这个怎么样:

(from b in Tbls
where (from a in Tbls
       where a.StateCode == b.StateCode
       group a by a.StateCode into grp
       where grp.Count () == 1
       select grp).Count() > 0
select b).Dump();

这是我用来测试它的 SQL:

create table tbl (StateCode varchar(5), CityCode varchar(5))

insert tbl values ('01', '001')
insert tbl values ('01', '002')
insert tbl values ('02', '001')
insert tbl values ('03', '001')
insert tbl values ('03', '002')
insert tbl values ('03', '003')
于 2013-10-26T08:31:51.833 回答