Question

I need a Linq query to include an item in the result only if a value exists in another list. I've been looking at here and in MSDN doc and just can't get the syntax right.

I have a list of user roles:

var userRoles = _identityManager.GetUserRoles(userId);
var roles = userRoles.Select(role => role.RoleId).ToList();

And I want the query against DbContext to include an item only if its AccessRole is in the roles list:

documents = context.ClientDocuments
.Where(d => d.ClientID == clientId)
//&& roles.contains d.AccessRole // pseudo code
.OrderByDescending(d => d.DateCreated)
.Select(
    doc => new ClientDocumentDto()
    {
        DocumentID = doc.ClientDocumentID,
        Name = doc.Name,
        Project = doc.Project,
        DocumentType = doc.DocumentType,
        DateCreated = doc.DateCreated,
        AccessRole = doc.AccessRole
    });
Was it helpful?

Solution

How about specifying the condition in the Where clause?

documents = context.ClientDocuments
.Where(d => d.ClientID == clientId && roles.Contains(d.AccessRole))

.OrderByDescending(d => d.DateCreated)
.Select(
    doc => new ClientDocumentDto()
    {
        DocumentID = doc.ClientDocumentID,
        Name = doc.Name,
        Project = doc.Project,
        DocumentType = doc.DocumentType,
        DateCreated = doc.DateCreated,
        AccessRole = doc.AccessRole
    });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top