views:

50

answers:

3

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. Thanks for any help.

+1  A: 
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);
Sorax
+1  A: 

Couldn't you just do...

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

or if you just want to know if there exist any...

select new
{
  DscId = appendGeo.Key,
  ThrowException = appendGeo.Any(n => n.Count > 1)
};
Nix
A: 
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()
          };

Can't you add a where clause before the select? It worked in my example but I'm not sure without seeing the data.

Dismissile
I was hoping to count where duplicate DSCID values occur in the joined table, not simply whether the joined table had a record count greater than 1. Thanks a lot though for the reply.
jrubengb