Get Most Recent Created On Record from Retrieved Entity Collection In Plugin

Sometimes, you may have a requirement to get the most recently created on record from the entity collection you have retrieved.

Instead of playing around a lot with coding and .net stuff, Dynamics CRM fetch XML and QueryExpression provides a way to sort records Ascending or descending.

Therefore, While retrieving records in FetchXML, do this :

<entity name='entityname'>
 <attribute name='atrributename1' /> 
   <attribute name='atrributename2' />    
    <attribute name ='attributename3' />                       
      <order attribute='createdon' descending='true' /> 
     <filter type='and'>                                  
     <condition attribute='statecode' operator='eq' value='0' />
   </filter>
</entity>

Or in Query Expression:

QueryExpression qe = new QueryExpression(entityName);
FilterExpression fe = new FilterExpression();
qe.ColumnSet = new ColumnSet(true);
qe.Orders.Add(new OrderExpression(columnname, ordertype)); 
service.RetrieveMulti ple(qe);

 

when Execute them , you will get the desired record on the top which can be access by simply by doing retrievedResult[0] or :

firstRecord= retrievedResult.Entities.First(); //first method.

firstrecord

I hope this helps!

cheers!

 

Advertisement