views:

321

answers:

3

Hi there

I have a collection of Roles.GetAllRoles() on Membership Providers. Now I have one role "System Administrator" that I would like to remove from that list so I can use in my list. How do I do this?

public void AssignUserToRoles_Activate(object sender, EventArgs e)
        {
            try
            {
                AvailableRoles.DataSource = Roles.GetAllRoles();
                AvailableRoles.DataBind();
            }
            catch (Exception err)
            {
                //
            }
        }
A: 

If you wanted you could use LINQ to convert the array into a list...

var roles = Roles.GetAllRoles().ToList();
roles.Remove("Administrator"); //Yank out the admin role...

AvailableRoles.DataSource = roles;
AvailableRoles.DataBind();

All your databinding will work just fine with a List<String>

UPDATE:

ToList<T>() is an extension method that is part of the .Net 3.5 bundle. You need to make sure your project is targeting that framework version, and you need to make sure your project has a reference to System.Core.

Once you have that reference you need to add a Using statement at the top of the file your code is located at:

using System.Linq;

If you have all those those things, then you should start seeing a bunch of new extension methods show up in intellisense.

Josh
This is weird. I don't get the ToList() after Roles.GetAllRoles() ?!?!
dewacorp.alliances
@dewacorp: data binding works with collection interfaces, including IEnumnerable<T>, not just concrete collection types.
Richard
A: 

Roles.GetAllRoles() returns a string array which you can filter using this code:

        string[] roles = Roles.GetAllRoles();
        var v = from role in roles
                where role != "System Administrator"
                select role;

        AvailableRoles.DataSource = v;
        AvailableRoles.DataBind();
TheVillageIdiot
+2  A: 

It can achieved without adding any extra lines to your code.

public void AssignUserToRoles_Activate(object sender, EventArgs e)
        {
            try
            {
                AvailableRoles.DataSource = Roles.GetAllRoles().Except(new [] {"System Administrator"});
                AvailableRoles.DataBind();
            }
            catch (Exception err)
            {
                //
            }
        }

Comment: not sure why do you need try...catch here. But whatever, this solution looks neat to me.

Amby
Can not do this either: Roles.GetAllRoles().Except(new [] {"System Administrator"}); No methods for Except ?!!?
dewacorp.alliances
"using System.Linq".I thought this was obvious. This is an extension method in "System.Core" dll.
Amby