目前,我有以下内容,来自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();
}
我遇到的问题是,如果我有Doe,John它工作正常,但如果我有Admin01,它会崩溃,因为它无法找到第二部分。如何更改它,以便如果它只有一个单词,它也会起作用?
答案 0 :(得分:6)
首先,我会将它投影到复合类型,以便您不会反复拆分。 然后我会用? :运营商。然后投射回去获得原始类型。
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 );
答案 1 :(得分:0)
您可以尝试这样做:
// 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(); }