Search in EntityCollection using Linq in CRM 2011

If you want to search in a EntityCollection without iterating through the collection then here is the example:

First make a query expression to retrieve all the records

QueryExpression queryProduct = new QueryExpression
EntityName = “product”,
ColumnSet = new ColumnSet(“quantity”, “productid”),
EntityCollection productCollection = service.RetrieveMultiple(queryProduct);

Now use the below method to retrieve single record from the entity collection using the id condition or you can define your own condition like where product.Attributes[“FieldName”]== criteriaValue

private IEnumerable<Entity> GetEntity(Guid criteriaValue,EntityCollection theEntityCollection)
IEnumerable<Entity> products = from product in theEntityCollection.Entities.AsEnumerable()
where product.Id == criteriaValue
select product;
return (IEnumerable<Entity>)products;

After this you can retieve the single Entity record by using the below code

foreach (Entity retrieve in service.RetrieveMultiple(query).Entities)

EntityReference productid = (EntityReference)productRecord.Attributes[“productid”]; 

Entity productRecord= GetEntity(productid.Id, productCollection).First<Entity>();

decimal qty= (decimal)productRecord.Attributes[“quantity”];


So by using this you don’t have to make service call everytime to retrieve the particular record inside the loop.

Namaste 🙂



One thought on “Search in EntityCollection using Linq in CRM 2011

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s