Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I would like to store in c# code some list or collection or what else to store SPUser and SPGroup objects. After this I would like to do some foreach loop and do some logic.

share|improve this question

3 Answers 3

I have found the solution:

List<SPPrincipal> usersAndGroups = new List<SPPrincipal>();
share|improve this answer
    
If you're happy with this as a solution, please can you mark this post as the answer. It'll help others in the future. –  Steven D Andrews Feb 21 '13 at 17:00

Based on a blog post I found, I have written the following code:

private static List<SPUser> ListUsers(SPWeb web, SPPrincipal group)
{
    try
    {
        web.Site.CatchAccessDeniedException = false;
        var users = new List<SPUser>();
        foreach(SPUser user in web.SiteUsers)
        {
            using(var userContextSite = new SPSite(web.Site.ID, user.UserToken))
            {
                try
                {
                    using (var userContextWeb = userContextSite.OpenWeb(web.ID))
                    {
                        try
                        {
                            if (userContextWeb.SiteGroups[group.Name]
                                .ContainsCurrentUser)
                                    users.Add(user);
                        }
                        catch (SPException)
                        {
                            // group not found, continue
                        }
                    }
                }
                catch(UnauthorizedAccessException)
                {
                    // user does not have right to open this web, continue
                }
            }
        }
        return users;
    }
    finally
    {
        web.Site.CatchAccessDeniedException = true;
    }
}

I don't like the fact that I have to impersonate every single user, and this code will only find AD users that have already been imported into SharePoint (so an SPUser exists for them), but that's good enough for me.

Above answer has been copied from this Source :

share|improve this answer

I am not sure whether I understand your question correctly, but if you need to get some users and make foreach loop (and do some logic) on them on the same time when they were fetched and they will not be used later, you definetely need to use collection for it. If you need results of some logic later, you can save them to a list.

share|improve this answer

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.