Get the option set values of a field in an entity in Dynamics CRM using SDK and C# code


Today we got a requirement to retrieve OptionSet values of a field from an entity in CRM. Here is the sample code of it.

public static OptionSetMetadataGetOptionSetsValuesInAnEntity(stringentityName, string attributeName, IOrganizationService service)
       string AttributeName = attributeName;
       string EntityLogicalName = entityName;
       RetrieveEntityRequest retrieveDetails = new RetrieveEntityRequest
             EntityFilters = EntityFilters.All,
             LogicalName = EntityLogicalName
       RetrieveEntityResponse retrieveEntityResponseObj = (RetrieveEntityResponse)service.Execute(retrieveDetails);
       Microsoft.Xrm.Sdk.Metadata.EntityMetadata metadata = retrieveEntityResponseObj.EntityMetadata;
       Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata picklistMetadata = metadata.Attributes.FirstOrDefault(attribute => String.Equals(attribute.LogicalName, attributeName, StringComparison.OrdinalIgnoreCase)) as Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata;
       Microsoft.Xrm.Sdk.Metadata.OptionSetMetadata options = picklistMetadata.OptionSet;
      // Use below code to get the Option Set Item Name from Value (optionSetValue)
      //IList OptionsList = (from o in options.Options
      //                                     where o.Value.Value == optionSetValue
      //                                     select o).ToList();
      // string optionsetLabel = (OptionsList.First()).Label.UserLocalizedLabel.Label;
      return options;

Hope this helps.

Happy CRM’ing


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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s