Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Is there a simpler and optimized way to calculate listAdminCorePriveleges and privileges ?

public string[] GetPrivilegesForUserByPersonEntityId(int personEntityId)
    {
        var listPrivileges = new List<string>();
        var listAdminCorePriveleges = (_accountRepository.AsQueryable()
          .Where(acc => acc.PersonEntityId == personEntityId)
          .Select(acc => acc.AccountAdminPositionAssignments.Where(aap => aap.IsLocked == false && aap.IsObsolete == false).Select(aap => aap.AdminPosition.AdminType.AdminPrivileges))
          ).AsEnumerable();

        foreach (var adminCorePriveleges in listAdminCorePriveleges)
        {
            foreach (var adminCorePrivelege in adminCorePriveleges)
            {
                listPrivileges.Add(adminCorePrivelege.Name); 
            }
        }
        string[] privileges = listPrivileges.Distinct().ToArray();
        return privileges;
    }
share|improve this question

1 Answer 1

up vote 2 down vote accepted

To know for sure what exactly is inefficient you'd need to hook up a profiler.

Code wise you should be able to do it all in one query if I'm not mistaken:

return _accountRepository.AsQueryable()
            .Where(acc => acc.PersonEntityId == personEntityId)
            .SelectMany(acc => acc.AccountAdminPositionAssignments
                                  .Where(aap => !aap.IsLocked && !aap.IsObsolete)
                                  .SelectMany(aap => aap.AdminPosition.AdminType.AdminPrivileges.Select(p => p.Name)))
            .Distinct()
            .ToArray();

This will in theory also move the name selection and distinct filtering to the database which means that probably slightly less data has to be transferred. Adds a bit more work for the database server but that kind of stuff is what they should do well.

share|improve this answer
    
Is it good practice to write .Where(acc => acc.PersonEntityId == personEntityId && acc.AccountAdminPositionAssignments.Any(aap => !aap.IsLocked) && ...).SelectMany(acc => acc.AccountAdminPositionAssignments.SelectMany(aap => ... instead of yours? –  Iman Nov 24 '13 at 8:35
1  
@Iman: Not really sure. I like to filter at the place where I'm selecting the data from, but if your version yields a better query or you simply like it better then go for it. –  ChrisWue Nov 24 '13 at 9:18

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.