问题
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