I have this code which gives me a list of all the users by using my membership provider.
var users = Membership.GetAllUsers();
var usernames = new List<string>();
foreach(MembershipUser m in users)
usernames.Add(m.UserName);
I thought there should be an easier way to do this by using LINQ, but I can't seem to use LINQ on a MembershipUserCollection
Because MembershipUserCollection only implements IEnumerable
, not IEnumerable<MembershipUser>
, you need to use the Linq extension method Cast then then use other Linq extension methods:
Membership.GetAllUsers ().Cast<MembershipUser> ().Select (m => m.UserName);
You should be able to use LINQ, if you use the Cast<T>()
method on it first.
Like this:
var usernames = Membership.GetAllUsers().Cast<MembershipUser>().Select(x => x.UserName).ToList();
Generally an alternative to explicit casting is to use
OfType<MembershipUser>
so you have
var userList = Membership.GetAllUsers().OfType<MembershipUser>().ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With