Using Linq on MembershipUserCollection
Asked Answered
S

4

16

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

Supraorbital answered 10/1, 2012 at 19:27 Comment(0)
I
33

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);
Indaba answered 10/1, 2012 at 19:31 Comment(1)
I got the message "Evaluation time out" when sorting 30,000 recordsFustigate
K
3

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();
Kickoff answered 10/1, 2012 at 19:33 Comment(0)
M
2

Generally an alternative to explicit casting is to use

OfType<MembershipUser>

so you have

var userList = Membership.GetAllUsers().OfType<MembershipUser>().ToList();
Mulhouse answered 18/2, 2014 at 12:12 Comment(0)
G
1

I used this piece of code to create a generic list of Members:

List<Member> memberList = new List<Member>();
foreach (MembershipUser membershipUser in members)
{
    int id = Convert.ToInt32(membershipUser.ProviderUserKey);
    memberList.Add(new Member(id));
}
Gerardgerardo answered 25/4, 2012 at 13:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.