Retrieve User or Group from an SPFieldUser

Hello,

Recently I have create a timer job to alert users to have task on a SharePoint list.

On my list I have on column "Assigned To" and it can contains user or group.

This code test field value to determine if it an "SPUser" or "SPGroup" object and retrieve all assigned users :

  1. //Group or User are allowed      
  2. SPFieldUser userField = (SPFieldUser)item.Fields.GetField("AssignedTo");      
  3. SPFieldUserValue userFieldValue = (SPFieldUserValue)userField.GetFieldValue(item["AssignedTo"].ToString());      
  4.     
  5. var users = new List<SPUser>();    
  6. //Tries to get SPUser      
  7. if (userFieldValue.User != null)      
  8. {      
  9.     users.Add(userFieldValue.User);      
  10. }      
  11. else      
  12. {      
  13.     //if the field contain group      
  14.     SPGroup group = web.SiteGroups.GetByID(userFieldValue.LookupId);      
  15.     foreach (SPUser user in group.Users)      
  16.     {      
  17.         users.Add(user);      
  18.     }      
  19. }      
  20. foreach(var user in users)    
  21. {    
  22.       //implement your code here    
  23. }    
If you have any questions you can use comments section ;)