2013-08-06 35 views
2

目前,我有以下,從LDAP拉。如何按姓和名排序,然後按SamAccountName排序,哪裏並非所有名字都有第一個和最後一個?

// 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(); 
} 

我遇到的問題是,如果我有李四,約翰它工作正常,但如果我有Admin01,它崩潰,因爲它不能找到第二部分。我該如何改變它,如果它只有一個單詞,它也會起作用?

回答

5

首先,我會把它投射到一個複合型,讓你不拆了個遍。 然後我會用一個? :運營商。然後投影回原始類型。

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); 
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(); } 
相關問題