我阅读了一个.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类型的表达式
是什么导致了这个错误,我如何才能简单地正确地输出新排序的列表?
发布于 2014-02-13 11:57:40
其原因不是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[]可能不会给出您期望的结果。
https://stackoverflow.com/questions/21753478
复制相似问题