Marketing lists come in two flavours, static which are a simple list of contacts, accounts or leads and dynamic which are represented by a single query rather than by attaching each record to the list separately. This means if you need to access this information programmatically you have to include an extra step to make sure you get the data out regardless of the list type.
The code to do it is relatively simple and the function below is provided as a starting point.
public EntityCollection GetListMembers(Guid listId, IOrganizationService service) { // listId is the Guid of the marketing list you want to get the members for Entity maillist = (Entity)service.Retrieve("list", listId, new ColumnSet(new string[] { "type", "query" })); if ((bool)maillist["type"]) // type will be true if it is a dynamic list { if (maillist.Attributes.Contains("query")) // make sure a query is present { // query is stored as a FETCHXML query rather than a list of records string _FetchQuery = (string)maillist["query"]; var fetch = new FetchExpression(_FetchQuery); // get the results EntityCollection er = (EntityCollection)service.RetrieveMultiple(fetch); return er; // return the results } } else { // start of code to handle static mailing list items var query = new QueryExpression("listmember"); // query listmember query.ColumnSet.AddColumns(new ColumnSet(new string[] { "entityid", "entitytype" })); // set the columns you want returned query.Criteria.AddCondition("listid", ConditionOperator.Equal, listId); // add the listid of the marketing list EntityCollection er = (EntityCollection)service.RetrieveMultiple(query); return er; // return the results } }
The first thing the code does is check the Type field in the list entity. If the value is true then it is a dynamic list, otherwise it is a simple static list.
For a dynamic list the query is held in the query field as a FetchXml query. It is a simple matter you retrieve this and return the results of the query. The query results will contain all the basic information of each entity.
For a static list the links to each record are stored in a N:N relationship entity called listmember and you will be able to return a list of entity types and entity id that you will have to link to the actual entities if you want anything more than a basic list.