Search code examples
c#linqcountconditional-statementslinq-group

Linq join, group, count where count greater than value


I have the following linq expression that lets me join two tables, group them by a DSCID, and then get a count of the grouped values:

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

I need to take this just one step further by only selecting the counts greater than 1. I tried something like this:

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

but this didn't work. I need to be able to throw an error whenever qryGeoAppendQuery returns records with counts > 1, so ideally the query would be wrapped in an if statement.


Solution

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