3

目前,我有以下内容,从 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,它会崩溃,因为它找不到第二部分。我如何更改它,以便如果它只有一个词,它也可以工作?

4

2 回答 2

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 );
于 2013-08-06T21:05:00.290 回答
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(); }
于 2013-08-06T21:03:41.713 回答