You can use the following sample code to get a count of record. This sample is based on the email entity:
private int RetrieveEmailCount(Guid emailId)
{
int rc = 0;
StringBuilder sb = new StringBuilder();
sb.AppendLine("<fetch distinct='false' mapping='logical' aggregate='true'> ");
sb.AppendLine(" <entity name='email'> ");
sb.AppendLine(" <attribute name='activityid' alias='email_count' aggregate='count'/> ");
sb.AppendLine(" <filter type='and'>");
sb.AppendLine(" <condition attribute='XXX' operator='eq' value='" + filterValue + "' /> ");
sb.AppendLine(" </filter> ");
sb.AppendLine(" </entity> ");
sb.AppendLine("</fetch>");
EntityCollection totalCount = service.RetrieveMultiple(new FetchExpression(sb.ToString()));
if (totalCount.Entities.Count > 0)
{
foreach (var t in totalCount.Entities)
{
rc = (int)((AliasedValue)t["email_count"]).Value;
break;
}
}
return rc;
}