避免在foreach中打印某些行

时间:2015-04-01 08:22:53

标签: c# foreach

您好我想避免在我的foreach循环中打印某些行(有效帐户)(在GetSAM中),而不是打印所有内容。

当我尝试通过注释打印有效帐户的行(在valSAM中)时,在有效帐户曾经的区域中将是空白。我知道这是因为foreach循环遍历数据库中的所有变量。

我如何消除输出之间的空白?

GetSAM:

   //Get SAMAccount
    private static string GetSAM(string ldapAddress, string serviceAccountUserName, string serviceAccountPassword)
    {
        string ldapPath = "LDAP://" + ldapAddress;
        string ldapFilter = "(&(objectclass=user)(objectcategory=person))";
        DirectoryEntry directoryEntry = new DirectoryEntry(ldapPath, serviceAccountUserName, serviceAccountPassword);
        string readOutput;
        List<string> list = new List<string>();  
        List<int> invalid = new List<int>();
        using (DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry))
        {
            string samAccountName;
            directorySearcher.Filter = ldapFilter;
            directorySearcher.SearchScope = SearchScope.Subtree;
            directorySearcher.PageSize = 1000;
            using (SearchResultCollection searchResultCollection = directorySearcher.FindAll())
            {
                **foreach (SearchResult result in searchResultCollection)
                {
                    samAccountName = result.Properties["sAMAccountName"][0].ToString();
                    if (valSAM(samAccountName, ldapAddress, serviceAccountUserName, serviceAccountPassword)!= true)
                    {
                        invalid.Add('1');
                    }
                    list.Add(samAccountName);
                }  //end of foreach**
                // Count all accounts 
                int totalAccounts = list.Count;
                // Count all invalid accounts 
                int invalidAccounts = invalid.Count;
                Console.WriteLine("Found " + invalidAccounts + " invalid accounts out of " + totalAccounts + " user accounts.\nQuery in " + ldapAddress + " has finished.\n");
                Console.WriteLine("Press [enter] to continue.\n");
                readOutput = Console.ReadLine();
            }//SearchResultCollection will be disposed here
        }
        return readOutput;
    }

valSAM:

//Validate SAMAccount
    private static bool valSAM(string samAccountName, string ldapAddress, string serviceAccountUserName, string serviceAccountPassword)
    {
        string ldapPath = "LDAP://" + ldapAddress;
        DirectoryEntry directoryEntry = new DirectoryEntry(ldapPath, serviceAccountUserName, serviceAccountPassword);
        StringBuilder builder = new StringBuilder();
        bool accountValidation = false;
        //create instance fo the directory searcher
        DirectorySearcher desearch = new DirectorySearcher(directoryEntry);
        //set the search filter
        desearch.Filter = "(&(sAMAccountName=" + samAccountName + ")(objectcategory=user))";
        //find the first instance
        SearchResult results = desearch.FindOne();
        using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, ldapAddress))
        {
            //if users are present in database
            if (results != null)
            {
                //Check if account is activated
                bool isAccountActived = IsActive(results.GetDirectoryEntry());
                //Check if account is expired or locked
                bool isAccountLocked = IsAccountLockOrExpired(results.GetDirectoryEntry());
                accountValidation = ((isAccountActived != true) || (isAccountLocked));
                //account is invalid 
                if (accountValidation)
                {
                    builder.Append("User account " + samAccountName + " is invalid. ");
                    if ((isAccountActived != true) && (isAccountLocked))
                    {
                        builder.Append("Account is inactive and locked or expired.").Append('\n'); ;
                    } else if (isAccountActived != true)
                    {
                        builder.Append("Account is inactive.").Append('\n'); ;
                    }
                    else if (isAccountLocked)
                    {
                        builder.Append("Account is locked or has expired.").Append('\n'); ;
                    }
                    else
                    {
                        builder.Append("Unknown reason for status. Contact admin for help.").Append('\n'); ;
                    }
                    accountValidation = false;
                }
                //account is valid
                if ((isAccountActived) && (isAccountLocked != true))
                {
                 **//builder.Append("User account " + samAccountName + " is valid.").Append('\n');
                    accountValidation = true;
                }
            }
            else Console.WriteLine("Nothing found.");
            Console.WriteLine(builder);
        }//end of using
        return accountValidation;
    }

1 个答案:

答案 0 :(得分:0)

你可能只想写一个如果构建器有东西,否则它会打印一个空行。即,改变

Console.WriteLine(builder);

if (builder.Length > 0)
{
    Console.WriteLine(builder);
}

或只是

Console.Write(builder);

如果您要处理构建器本身中的所有新行。如果您要这样做,请使用StringBuilder.AppendLine()而不是像这样硬编码'\ n'。