Can someone please provide a sample code for retrieving leads by email in CRM SDK? Is there any built in function that works like this?
Guid leadID = someLeadManager.GetByEmail(email);
Assuming that you've obtained the service, you can execute the following query.
private Guid GetGuidByEmail(String email)
{
QueryExpression query = new QueryExpression
{
EntityName = "lead",
ColumnSet = new ColumnSet("emailaddress1"),
Criteria = new FilterExpression
{
Filters =
{
new FilterExpression
{
Conditions =
{
new ConditionExpression(
"emailaddress1", ConditionOperator.Equals, email)
}
}
}
}
};
Entity entity = service.RetrieveMultiple(query).Entities.FirstOrDefault();
if(entity != null)
return entity.Id;
return Guid.Empty;
}
Now, if you need filtration for a match of part of the email, the query gets shorter, and instead, you can do the selection using LINQ like this.
private IEnumerable<Guid> GetGuidsByEmail(String email)
{
QueryExpression query = new QueryExpression
{
EntityName = "lead",
ColumnSet = new ColumnSet("emailaddress1")
};
IEnumerable<Entity> entities = service.RetrieveMultiple(query).Entities;
return entities
.Where(element => element.Contains("emailaddress1"))
.Where(element => Regex.IsMatch(element["emailaddress1"], email))
.Select(element => element.Id);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With