在Linq获得分组总记录

时间:2013-04-19 11:38:47

标签: c# .net linq entity-framework

我在SQL中有一个查询,想将其转换为Linq。我的查询是:

select count(tbs.tbsid) as CNTSeats,tbm.BusNo
from tdp_tourpackageschedule tps
join tdp_tourpackage tp on tp.TourID = tps.FK_TourID
join tdp_tourbusseats tbs on tbs.tbsid = tps.fk_tbsid
join tdp_tourbusmaster tbm on tbm.tbid = tbs.fk_tbid
where fk_tdid = @FKTDID and fk_TourID = @FKTourID and IsOpen = 1
group by tbm.BusNo

我试过这段代码:

var tourAvail = (from ts in entities.tdp_TourPackageSchedule
                 join tp in entities.tdp_TourPackage on ts.FK_TourID equals tp.TourID
                 join tbs in entities.tdp_TourBusSeats on ts.FK_TBSID equals tbs.TBSID
                 join tb in entities.tdp_TourBusMaster on tbs.FK_TBID equals tb.TBID
                 where ts.FK_TDID == TDID && ts.FK_TourID == TourID && ts.IsOpen == 1
                 group tb by tb.BusNo into cnt
                 select new
                 {
                     //BusNo = cnt.bu
                     //Count = cnt.Select(x => x.tdp_TourBusSeats).Distinct().Count()
                 });

我不知道如何获取记录,任何人都可以提供帮助?

1 个答案:

答案 0 :(得分:1)

做:

var tourAvail = (from ts in entities.tdp_TourPackageSchedule
                 join tp in entities.tdp_TourPackage on ts.FK_TourID equals tp.TourID
                 join tbs in entities.tdp_TourBusSeats on ts.FK_TBSID equals tbs.TBSID
                 join tb in entities.tdp_TourBusMaster on tbs.FK_TBID equals tb.TBID
                 where ts.FK_TDID == TDID && ts.FK_TourID == TourID && ts.IsOpen == 1
                 group tb by tb.BusNo into cnt
                 select new
                 {
                     BusNo = cnt.Key,
                     Count = cnt.Count()
                 }).ToList();