【问题标题】:Linq join, group, count where count greater than valueLinq join, group, count where count 大于 value
【发布时间】:2011-04-30 09:02:12
【问题描述】:

我有以下 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 返回计数 > 1 的记录时抛出错误,因此理想情况下,查询将包含在 if 语句中。

【问题讨论】:

    标签: c# linq count conditional linq-group


    【解决方案1】:
    "SELECT  [SubsNumber], sum([Usage_MB])/1024 as GB FROM [VASCDR].[dbo].[nrmSubsDailyMBUsage] where SubsNumber ='" + textBox1.Text.Trim() + "'" group by [SubsNumber] ;
    

    是如何用c#做到的

    【讨论】:

      【解决方案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
                where appendGeo.Count() > 1
                select new
                {
                  DscId = appendGeo.Key,
                  DscIdCount = appendGeo.Count()
                };
      

      你不能在选择之前添加一个 where 子句吗?它在我的示例中有效,但我不确定没有看到数据。

      【讨论】:

      • 我希望计算连接表中重复 DSCID 值出现的位置,而不仅仅是连接表的记录数是否大于 1。非常感谢您的回复。
      【解决方案3】:

      你就不能……

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

      【讨论】:

        【解决方案4】:
        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);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-07-09
          • 1970-01-01
          • 2018-11-16
          • 2023-03-04
          相关资源
          最近更新 更多