首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尝试使用IOrderedEnumerable输出C#列表

尝试使用IOrderedEnumerable输出C#列表
EN

Stack Overflow用户
提问于 2014-02-13 11:53:13
回答 1查看 2.5K关注 0票数 1

我阅读了一个.csv文件,进行了一些格式化,将每一行分隔到其列中,并将结果数组添加到列数组中。接下来,我使用IOrderedEnumerable命令数组列表,以便按字母顺序排列第二列,然后尝试将这个新排序的列表放到屏幕上。这是我坚持的最后一部分。

这就是我所尝试的:

代码语言:javascript
复制
// 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类型的表达式

是什么导致了这个错误,我如何才能简单地正确地输出新排序的列表?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-13 11:57:40

其原因不是IEnumerableIOrderedEnumerable支持索引,而是显示错误。

要显示排序结果,可以使用foreach枚举集合:

代码语言:javascript
复制
// display the newly ordered list
foreach (var user in usersByUsername)
{
    Console.WriteLine(string.Join(", ", user));
}

或者可以将结果转换为列表并使用索引:

代码语言:javascript
复制
//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[]可能不会给出您期望的结果。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21753478

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档