2

I am making a simple birthday calendar webpart for Sharepoing 2010.

I need to iterate through all users of a site and show those who have birthday on said date. I need to present users in alphabetical order of their names.

I can iterate through user list by doing ilke this:

SPSite currentSite = ...
ServerContext ospServerContext = ServerContext.GetContext(currentSite);
UserProfileManager ospUserProfileManager = new UserProfileManager(ospServerContext);
foreach (UserProfile ospUserProfile in ospUserProfileManager) { ... }

However, then i have no control over the order of profiles. Is there any built in way to order the profiles by some simple rule, or do i have to make a Dictionary(string,UserProfile), fill it from UserProfileManager, then sort it by its key, and then do foreach for its members?

Thanks!

Istrebitel
  • 2,963
  • 6
  • 34
  • 49

1 Answers1

3

Add using block:

using System.Linq;

Create a collection of user profiles:

var collection = new List<UserProfile>();

populate it:

foreach (UserProfile ospUserProfile in ospUserProfileManager) 
{ 
   collection.Add(ospUserProfile);
}

then sort it:

var sorted = collection.OrderBy(p => p.PropertyToSort);
Anton Sizikov
  • 9,105
  • 1
  • 28
  • 39
  • Hmm its strange but VS2010 complains about OrderBy being not a valid member of List... what am i doing wrong? – Istrebitel Sep 13 '12 at 13:25
  • If you're going to go down the LINQ route, you may as well go the whole hog and use `var collection = ospUserProfileManager.Cast().ToList()` instead of a `foreach` loop or, better, go straight from the `Cast` into the `OrderBy` without making a `List`. And do the birthday-filtering `Where` before the `OrderBy` for efficiency... – Rawling Sep 13 '12 at 13:30
  • *ToList()* waits an *IEnumerable* source, but *ospUserProfileManager* does not inherit it. – Anton Sizikov Sep 13 '12 at 13:35
  • My mistake, I assumed if you could call `foreach` on it you could call `Cast<>` to get a nicely typed enumerator. – Rawling Sep 13 '12 at 13:38