简体   繁体   中英

c# foreach loop formatting

I have the following C# code that provide the below output but I need some help to change it to the below desire output. How can I rewrite my code to provide the "Required output"?

SearchResultSet results = session.Search(searchRequest);
results.GetCount());
IEnumerable columns = results.GetColumns();
while (results.HasNext())
{
    foreach (string column in columns)
    {
        Console.WriteLine(column + ": " + results.GetString(column));
    }
    Console.WriteLine();
}

Output:

Unique_ID: 234556
Address: 555 John Street
City: Orlando
State: FL
Zip: 32751
Unique_ID: 5326536
Address: 1200 Avenue of America
City: New York
State: NY
Zip: 10016
Unique_ID: 4815585
Address: 149 Madison Avenue
City: New York
State: NY
Zip: 10016

Required Output:

Unique_ID|Address|City|State|Zip
234556|555 John Street|Orlando|FL|32751
5326536|1200 Avenue of America|New York|NY|10016
4815585|149 Madison Avenue|New York|NY|10016

Hmmm, I haven't tested it. I hope it helps you. I would do it using two foreach inside the main while

SearchResultSet results = session.Search(searchRequest);
 results.GetCount()); 
 IEnumerable columns = results.GetColumns();
 bool printColumns = true;
        while (results.HasNext())
        {
            if(printColumns){
                foreach (string column in columns)
                {
                    Console.WriteLine(String.Format("{0}|", column)); //Will print Unique_ID|Address|etc...
                }               
            }
            printColumns = false;
            foreach (string column in columns)
            {
                Console.Write(String.Format("{0}|", results.GetString(column))); //Will print 234556|555 JOHN STREET|Orlando|FL|32751
            }           
            Console.WriteLine();
        }

EDIT:

The previous code keeps a pipe at the end of the strings. If you don't want this, you should use a String variable, concatenate the result, and after each foreach , you simply do a susbtr to remove the ending pipe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM