Please try below code:
1. Using simple retrieve
/// <summary>
/// retrieve data for field "XYZ" for record
/// "new_xyz" is the Logical name of the XYZ field on the contact form
/// </summary>
public void retrieveContactDetailsforSingleRecord()
{
try
{
Entity entContact = _service.Retrieve("contact", new Guid("recordid"), new ColumnSet("new_xyz"));
if (entContact.Attributes.Contains("new_xyz"))
{
string xyzValue = entContact["new_xyz"].ToString();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
2. Using Retrieve multiple
/// <summary>
/// Retrieve Contact Details for Mutliple Records using Fetch XML
/// </summary>
public void retrieveContactDetailsUsingFetchXML()
{
try
{
string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='contact'>
<attribute name='new_xyz' />
<order attribute='new_xyz' descending='false' />
<filter type='and'>
<condition attribute='new_xyz' operator='not-null' />
</filter>
</entity>
</fetch>";
EntityCollection entContactColl = _service.RetrieveMultiple(new FetchExpression(fetchXml));
if (entContactColl != null && entContactColl.Entities.Count > 0)
{
foreach (Entity entContact in entContactColl.Entities)
{
if (entContact.Attributes.Contains("new_xyz"))
{
string xyzValue = entContact["new_xyz"].ToString();
}
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
3. Using Linq:
/// <summary>
/// Retrieve Contact Details Using Linq
/// </summary>
public void retrieveContactDetailsUsingLinq()
{
try
{
var contactDetails = from contactEntity in _context.CreateQuery("contact")
select new
{
xyzValue = contactEntity.Attributes.Contains("new_xyz") ? (string)contactEntity["new_xyz"] : string.Empty,
};
foreach (var recordsContact in contactDetails)
{
if (recordsContact.xyzValue != null)
{
string XYZ = recordsContact.xyzValue;
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
4. Using Query Expression
/// <summary>
/// Retrieve Contact Details Using QueryExp
/// </summary>
public void retrieveContactDetailsUsingQueryExp()
{
try
{
QueryExpression getAllRecords = new QueryExpression();
getAllRecords.EntityName = "contact";
getAllRecords.ColumnSet = new ColumnSet("new_xyz");
ConditionExpression con = new ConditionExpression("new_xyz", ConditionOperator.ContainValues);
EntityCollection entContactColl = _service.RetrieveMultiple(getAllRecords);
if (entContactColl != null && entContactColl.Entities.Count > 0)
{
foreach (Entity entContact in entContactColl.Entities)
{
if (entContact.Attributes.Contains("new_xyz"))
{
string xyzValue = entContact["new_xyz"].ToString();
}
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
Hope this helps.
Thanks!