我在.csv文件中读过,完成了一些格式化,将每一行分隔到其列中,并将生成的数组添加到列数组列表中。接下来,我使用IOrderedEnumerable
对数组列表进行了排序,按字母顺序按第二列排序,然后我尝试将这个新排序的列表放到屏幕上。这是我坚持的最后一部分。
这就是我的尝试:
// attempt to read file, if it fails for some reason display the exception error message
try
{
// create list for storing arrays
List<string[]> users = new List<string[]>();
string[] lineData;
string line;
// read in stremreader
System.IO.StreamReader file = new System.IO.StreamReader("dcpmc_whitelist.csv");
// loop through each line and remove any speech marks
while((line = file.ReadLine()) != null)
{
// remove speech marks from each line
line = line.Replace("\"", "");
// split line into each column
lineData = line.Split(';');
// add each element of split array to the list of arrays
users.Add(lineData);
}
//sort this list by username ascending
IOrderedEnumerable<String[]> usersByUsername = users.OrderBy(user => user[0]);
// display the newly ordered list
for (int i = 0; i <= users.Count; i++)
{
Console.WriteLine(usersByUsername[i]);
}
// after loading the list take user to top of the screen
Console.SetWindowPosition(0, 0);
}
catch (Exception e)
{
// Let the user know what went wrong when reading the file
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
但这会给出错误:
无法将带有[]的索引应用于类型的表达式 system.linq.iorderedenumerable
导致此错误的原因是什么?我如何才能正确输出新排序的列表?
答案 0 :(得分:3)
原因既不是IEnumerable
也不是IOrderedEnumerable
支持索引,显示错误。
要显示有序结果,您可以使用foreach
枚举集合:
// display the newly ordered list
foreach (var user in usersByUsername)
{
Console.WriteLine(string.Join(", ", user));
}
或者您可以将结果转换为列表并使用索引:
//sort this list by username ascending
IList<String[]> usersByUsername = users.OrderBy(user => user[0]).ToList();
// display the newly ordered list
for (int i = 0; i <= users.Count; i++)
{
Console.WriteLine(string.Join(", ", usersByUsername[i]));
}
另请注意string.Join
的使用情况 - 仅打印string[]
可能无法获得您期望的结果。