C# Asp.net Membership.GetAllUsers order by email

耗尽温柔 提交于 2020-01-03 16:47:59

问题


I am using Membership.GetAllUsers() to get my user list. I would like to have the list returned sorted by email address as I need to flag some accounts with duplicate emails.

Membership.GetAllUsers() seems to order by username by default. Is there a way to change this behavior?


回答1:


If you can live with a generic list rather than a MembershipUserCollection:

Membership.GetAllUsers().Cast<MembershipUser>().OrderBy(x => x.Email).ToList();

Use OrderBy(x => x.Email, StringComparer.OrdinalIgnoreCase) if you want a case-insensitive sort of the email address.

Membership code actually predates generics (it was integrated into .NET 2.0 from a .NET 1.1 development), hence MembershipUserCollection does not implement generic interfaces.

Given your earlier question, you may be interested in other LINQ-style manipulations. For example the following will give you a dictionary whose keys are email addresses (case-insensitive), and whose values are lists of corresponding MembershipUser objects, sorted by last activity date descending:

var dictionary = Membership.GetAllUsers().Cast<MembershipUser>()
    .GroupBy(x => x.Email, StringComparer.OrdinalIgnoreCase)
    .ToDictionary(
                  x => x.Key, 
                  x =>x.OrderByDescending(u => u.LastActivityDate).ToList()
                 );



回答2:


The following code should do it, but it may not have the best performance.

Membership.GetAllUsers().Cast<MembershipUser>().OrderBy(m => m.Email);

It does the sorting in memory, rather than as a db query.




回答3:


Membership.GetAllUsers().OrderBy(user => user.Email).ToList();


来源:https://stackoverflow.com/questions/11366838/c-sharp-asp-net-membership-getallusers-order-by-email

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!