How to sort by first and last name, then by SamAccountName where not all names have a first and last?

不问归期 提交于 2020-01-04 02:06:24

问题


Currently, I have the below, pulling from LDAP.

// Get context, based on currently logged on user
PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, Environment.UserDomainName);
// Search for the "Domain Users" group, with domain context
GroupPrincipal group = GroupPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, "Domain Users");
if(group != null) {
    List<Principal> members = null;
    members = group.GetMembers(false)
        .OrderBy(principal => principal.Name).ToList();
        List<Principal> Principals = members
        .OrderBy(a => a.Name.Split(',')[0])
        .ThenBy(a => a.Name.Split(',')[1])
        .ThenBy(a => a.SamAccountName).ToList();
}

The problem I run into is that if I have Doe,John it works fine, but if I have Admin01, it crashes because it can't find the second part. How do I change it so that if it is only one word it will work as well?


回答1:


First, I would project it to a compound type so that you don't split over and over. Then I would use a ? : operator. Then project back to get the original type.

members
  .Select( m => new { member = m, split = m.Name.Split(',') } )
  .OrderBy( a => a.split[0] )
  .ThenBy( a => a.split.Count() > 1 ? a.split[1] : string.Empty )
  .ThenBy( a => a.member.SamAccountNamr )
  .Select( a => a.member );



回答2:


You can try doing like this:

// Get context, based on currently logged on user PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, Environment.UserDomainName); // Search for the "Domain Users" group, with domain context GroupPrincipal group = GroupPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, "Domain Users"); if(group != null) {
    List<Principal> members = null;
    members = group.GetMembers(false)
        .OrderBy(principal => principal.Name).ToList();
        List<Principal> Principals = members
        .OrderBy(a => a.Name.Split(',')[0])
        .ThenBy(a => a.Name.Split(',').Length>1? a.Name.Split(',')[1]:a.Name.Split(',')[0])
        .ThenBy(a => a.SamAccountName).ToList(); }


来源:https://stackoverflow.com/questions/18090329/how-to-sort-by-first-and-last-name-then-by-samaccountname-where-not-all-names-h

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