A few time we need to pass multiple parameters to QueryExpression to fetch required entities. I have seen code with multiple calls instead of passing multiple parameters, and of course avoiding multiple calls is efficient.
In code reviews, I also have seen hard coded Guids or people looping through collections to obtain Guids. In some situations, these can be the “only” or best options but often it can be done in a cleaner way using LINQ.
This code example fetches Guids from an entity collection (which are connections) into Guid[] and then use Guid[] as a parameter in query expression.
EntityCollection result = null;
//Getting all GUIDs into a Guid array
Guid[] guids = connections.Entities.Select(con =>
con.GetAttributeValue<EntityReference>("record2id").Id).ToArray();
//Passing guid array in query expression
QueryExpression query = new QueryExpression("contact");
query.ColumnSet = new ColumnSet("name");
query.Criteria.AddCondition(new ConditionExpression("contactid", ConditionOperator.In, guids));
EntityCollection contacts = organizationService.RetrieveMultiple(query);
I hope it is helpful.
Enjoy your D365 day.