Displaying Online users using Linq-to-entities.

A frequently asked question on the forums is "how to display the Online users when using Membership ?

One possible way is to get the whole users and iterate through the collection and add the online user to a new temporary collection that holds the online users, like this :

foreach(MembershipUser muser in Users)
    if(muser.IsOnline)
        OnlineUsers.Add(muser);
GridView1.DataSource = OnlineUsers;
GridView1.DataBind();

Ok , we can get the same result in an easy way using Linq :

var onlineUsers = from MembershipUser u in Membership.GetAllUsers()
                  where u.IsOnline==true
                  select u;
 
GridView1.DataSource = onlineUsers;
GridView1.DataBind();

Of course both of methods will load the whole users to the memory because it mainly use Membership.GetAllUsers() method.

If you have a huge number of users , then you may consider an alternative way of doing this like using the Overloaded version of GetAllUsers Method to get users page by page.

No Comments