Linq join,group,count where count大于value

时间:2010-10-25 18:23:02

标签: c# linq count conditional linq-group

我有以下linq表达式,允许我连接两个表,按DSCID对它们进行分组,然后计算分组值:

var qryGeoApppendCount =
              from a in append
              join g in geo
              on a.Field<string>("RNO")
              equals g.Field<string>("RNO")
              group g by g.Field<int>("DSCID") into appendGeo
              select new
              {
                DscId = appendGeo.Key,
                DscIdCount = appendGeo.Count()
              };

我需要更进一步,只选择大于1的计数。我尝试过这样的事情:

select new
{
    DscId = appendGeo.Key,
    DscIdCount = appendGeo.Count(n => n.Count > 1)
};

但这不起作用。每当qryGeoAppendQuery返回带有计数&gt;的记录时,我都需要能够抛出错误。 1,理想情况下,查询将包含在if语句中。

4 个答案:

答案 0 :(得分:2)

var qryGeoApppendCount =
              (from a in append
              join g in geo
              on a.Field<string>("RNO")
              equals g.Field<string>("RNO")
              group g by g.Field<int>("DSCID") into appendGeo
              select new
              {
                DscId = appendGeo.Key,
                DscIdCount = appendGeo.Count()
              })
              .Where(a => a.DscIdCount > 1);

答案 1 :(得分:1)

你不能这么做......

select new
{
  DscId = appendGeo.Key,
  DscIdCount = appendGeo.Where(n => n.Count > 1).Count()
};

或者如果您只想知道是否存在......

select new
{
  DscId = appendGeo.Key,
  ThrowException = appendGeo.Any(n => n.Count > 1)
};

答案 2 :(得分:0)

var qryGeoApppendCount =
          from a in append
          join g in geo
          on a.Field<string>("RNO")
          equals g.Field<string>("RNO")
          group g by g.Field<int>("DSCID") into appendGeo
          where appendGeo.Count() > 1
          select new
          {
            DscId = appendGeo.Key,
            DscIdCount = appendGeo.Count()
          };

你不能在select之前添加where子句吗?它在我的例子中起作用,但我不确定没有看到数据。

答案 3 :(得分:0)

"SELECT  [SubsNumber], sum([Usage_MB])/1024 as GB FROM [VASCDR].[dbo].[nrmSubsDailyMBUsage] where SubsNumber ='" + textBox1.Text.Trim() + "'" group by [SubsNumber] ;

如何使用c#

进行操作