c#foreach循环格式化

时间:2015-10-10 00:20:20

标签: c# c#-4.0

我有以下提供以下输出的C#代码,但我需要一些帮助才能将其更改为以下所需的输出。如何重写我的代码以提供" Required输出"?

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

输出:

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

必需输出:

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 

1 个答案:

答案 0 :(得分:1)

嗯,我还没有测试过。我希望它对你有所帮助。我会在主foreach

中使用两个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();
        }

修改

前面的代码在字符串的末尾保留了一个管道。如果你不想这样,你应该使用String变量,连接结果,并在每个foreach之后,你只需要做一个susbtr来删除结束管道。