Question

I have read in a .csv file, done some formatting, seperated each line into its columns and added the resulting arrays into a list of arrays of columns. Next I have ordered the list of arrays using IOrderedEnumerable to order it by the second column ascending alphabetically, then I attempt to out put this newly ordered list to the screen. Its the last part that am I stuck on.

This is what I have attempted:

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

But this give the error:

cannot apply indexing with [] to an expression of type system.linq.iorderedenumerable

What is causing this error and how can I simply output the newly ordered list correctly?

Was it helpful?

Solution

The cause is neither IEnumerable nor IOrderedEnumerable support indexing, showing you the error.

To display the ordered result you can use foreach to enumerate the collection:

// display the newly ordered list
foreach (var user in usersByUsername)
{
    Console.WriteLine(string.Join(", ", user));
}

Or you can convert result to list and use indexing:

//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]));
}

Also note the usage of string.Join - just printing string[] might not give you the result you expect.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top