如何确保用户只被添加到列表一次

3 c# linq sharepoint-2007

我必须通过自定义搜索列出用户列表,其中我将所有组中的所有用户添加到sharepoint web上的权限列表中.我的问题是用户可以在多个组中,因此他们会多次添加到返回的列表中.我如何确保它们只被添加一次?

C#

// keywords is the whatever value a user types into the search textbox
private static IEnumerable<SPUser> GetUsers(SPWeb web, string keywords)
    {
        var oList = new List<SPUser>();
        var oListUsers = web.Groups.Cast<SPGroup>().SelectMany(grp => grp.Users.Cast<SPUser>().Where(user => user.Name.Contains(keywords))).ToList();

        foreach (SPUser user in oListUsers)
        {
            // My attempt here is to check if the list already contains the current item
            // but it seems to ignore it. I've tried counting too, but same outcome.
            if (!oList.Contains(user))
                oList.Add(user);
        }

        return oList;
    }
Run Code Online (Sandbox Code Playgroud)

Bal*_*a R 7

试试这个(而不是包含)

 if (! oList.Any(u => u.Name == user.Name ))
 {
      oList.Add(user);
 }
Run Code Online (Sandbox Code Playgroud)


Mar*_*k H 5

看起来您的SPUser类需要实现IEquatable<SPUser>包含才能按您的需要工作.