4

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?

Mr Lahey
  • 656
  • 3
  • 15
  • 31

3 Answers3

11

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()
                 );
Community
  • 1
  • 1
Joe
  • 122,218
  • 32
  • 205
  • 338
  • @peroija, It wasn't his, I edited his post instead of mine by mistake, then corrected it. – Joe Jul 06 '12 at 17:36
  • Thanks. I can live with a generic list for sure. This looks like it will be a great help but whats the best way to display the data? I tried your above code with return View(dictionary); but get an error when I try to iterate through the list like so: foreach (var users in dictionary). Error is: CS0103: The name 'dictionary' does not exist in the current context – Mr Lahey Jul 06 '12 at 18:23
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.

Spectre87
  • 2,374
  • 1
  • 24
  • 37
1
Membership.GetAllUsers().OrderBy(user => user.Email).ToList();
Joe
  • 122,218
  • 32
  • 205
  • 338
Akhil
  • 7,570
  • 1
  • 24
  • 23
  • 1
    This code won't actually compile, because `MembershipUserCollection` implements `IEnumerable`, and not `IEnumerable`. So LINQ extension methods won't work with the MembershipUserCollection. You first need to perform a cast operation on each element and convert it to an `IEnumerable` like this: `Membership.GetAllUsers().Cast()` – Spectre87 Jul 06 '12 at 17:35
  • No problem! I just noticed my typo - when I said "convert it to an `IEnumerable`", I meant "convert it to an `IEnumerable`". – Spectre87 Jul 06 '12 at 18:36