我有一个对象列表,其中包含几个带有字符串的列表。当我使用 foreach 循环显示对象列表时,一切都按原样显示,但是当我尝试在控制台中显示循环之外的两个对象时,我只看到第一个对象。我将不胜感激
items = new List<Object>();
items = fileOp.GetAnylisedCollection(PATH);
foreach (Object lists in items)
{
foreach (String list in (List<String>)lists)
{
Console.Write(list + " | ");
}
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine();
List<string> check = (List<string>)items[0];
Console.WriteLine(check[0] + check[1]);
返回列表的函数:
public List<Object> GetAnylisedCollection(String path)
{
int count = 0;
int prevSeparate = 0;
string line;
string toList = String.Empty;
List<Object> items = new List<Object>();
List<string> item = new List<string>();
StreamReader sr = new StreamReader(path);
//reading file line by line to string array
string[] str = new string[200];
while ((line = sr.ReadLine()) != null)
{
str[count] = line;
count++;
}
Array.Resize(ref str, count);
//array analysis and writing to collection
for (int i = 0; i < str.Length; i++)
{
char[] temp = str[i].ToCharArray();
for (int j = 0; j < temp.Length; j++)
{
toList = string.Empty;
if (temp[j].Equals('|'))
{
if (prevSeparate != 1) prevSeparate++;
for (int k = prevSeparate; k < j; k++)
{
toList += temp[k].ToString();
}
Console.WriteLine(toList);
item.Add(toList);
prevSeparate = j;
}
}
items.Add(item);
item = new List<string>();
Console.WriteLine();
}
return items;
}
控制台输出:
//使用foreach输出 | 波士顿洛根国际 (BOS) | 纽约约翰肯尼迪 (JFK) | 1200 | 10.11.2013 | | 波士顿洛根国际 (BOS) | 萨克拉门托国际 (SMF) | 430 | 10.11.2013 | | 克利夫兰霍普金斯国际 (CLE) | 萨克拉门托国际 (SMF) | 543 |1.11.2013| | 北京首都 (PEK) | 纽约约翰肯尼迪 (JFK) | 2500 | 13.11.2013 | | 莫斯科多莫杰多沃 (DME) | 波士顿洛根国际 (BOS) | 1230 | 15.11.2013 | | 华盛顿罗纳德·里根 (DCA) | 杜兰戈拉普拉塔 (DRO) | 340 | 14.11.2013 | | 亚特兰大哈兹菲尔德-杰克逊 ATL (ATL) | 华盛顿罗纳德·里根 (DCA) | 450 | 7.11.2013| | 萨克拉门托国际 (SMF) | 亚特兰大哈兹菲尔德-杰克逊 ATL (ATL) | 325 | 6.11.2013| | 纽约约翰肯尼迪 (JFK) | 北京首都 (PEK) | 2300 | 19.11.2013 | | 克利夫兰霍普金斯国际 (CLE) | 纽约约翰肯尼迪 (JFK) | 360 | 2.11.2013| //简单输出 波士顿洛根国际 (BOS)
这将显示为:
波士顿洛根国际 (BOS) 纽约约翰肯尼迪 (JFK)