2

私は機能する次のように書きましたが、すべてのユーザーを役割なしで取得するためのより効率的な方法があるかどうかを知りたいです。

using System.Collections.Generic;
using System.Linq;
using System.Web.Security;

public static IEnumerable<MembershipUser> GetUsersHavingNoRole() {
  var allUsers = Membership.GetAllUsers().Cast<MembershipUser>();
  foreach (var user in allUsers) {
    if (Roles.GetRolesForUser(user.UserName).Length.Equals(0)) {
      yield return user;
    }
  }
}
4

3 に答える 3

2

通常、ロールよりも多くのユーザーがいると思います-したがって、ロールを繰り返し処理し(return by )、それらのロールのいずれかでユーザーのリストを作成することは理にかなっているかもしれません(たとえば、それぞれのユーザーを作成して追加することによって) )によって返される役割、そしてそれとすべてのユーザーの違いを見つけます。したがって、LINQを使用している場合は、次を使用できます。Roles.GetAllRoles()HashSet<string>Roles.GetUsersInRole

var usersInRolesQuery = Roles.GetAllRoles()
                             .SelectMany(role => Roles.GetUsersInRole(role));

var usersInRoles = new HashSet<string>(usersInRolesQuery);
return Membership.GetAllUsers()
                 .Cast<MembershipUser>()
                 .Where(user => !usersInRoles.Contains(user.UserName));

もちろん、それでも同じ量のデータを処理しますが、関係するデータストアへのラウンドトリップが少なくなる可能性があります。

現在の方法がどれほど高価であるかを調べるために、アプリケーションのベンチマークを行いましたか?

于 2011-03-30T06:08:05.960 に答える
0

Depending on the amount of users, roles and relations in between them and the number of times you need this information, it might be worth it (had enough disclaimers yet?) to add an extra method to the (custom)Role Provider.

The native query that is required in the provider could be much more efficient than using LINQ the way you are doing now.

A lot depends on the factors in first line of this answer but also on the provider. Maintainability might also be an issue as you are adding a query that might not be supported in the future (next version of the provider)

于 2011-03-30T06:33:48.217 に答える
0

私があなたの質問を正しく理解していれば。このコードが役立つはずです!

MembershipUserCollection users = Membership.GetAllUsers();
MembershipUserCollection usersNoRoles = new MembershipUserCollection();

    foreach (MembershipUser user in users)
    {
        string[] roles = Roles.GetRolesForUser(user.UserName);

        // if roles empty
        if (roles.Count() == 0)
        {
            // Add User to a List for User with no Roles
            usersNoRoles.Add(user);
        }

   }
于 2011-06-29T14:04:25.783 に答える