0

I am attempting to read in a .csv file, do some formatting, split each line up into its column data and add the new array of seperated column data in to a list of arrays. Then I want to order the list in different ways. Currently just by username ascending alphabetically.

This is what I have attempted so far:

// create list for storing arrays
List<string[]> users;

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

}

IOrderedEnumerable<String[]> usersByUsername = users.OrderBy(user => user[1]);

Console.WriteLine(usersByUsername);

This gives one error:

Use of unassigned local variable 'users'

I don't understand why it is saying it is an unassigned variable? Why does the list not show when I run the program in Visual studios 2010?

crmepham
  • 4,676
  • 19
  • 80
  • 155

3 Answers3

5

Because objects need to be created before being used, The constructor sets up the object, ready for use this why you get this error

use something like this

List<string[]> users = new List<string[]>() ; 
BRAHIM Kamel
  • 13,492
  • 1
  • 36
  • 47
1

Use :

List<string[]> users= new List<string[]>();

instead of :

List<string[]> users;
Mohammad Arshad Alam
  • 9,694
  • 6
  • 38
  • 61
1

Visual Studio gave you Use of unassigned local variable 'users' error because you declare users variable but you never assign any value to it before while((line = file.ReadLine()) != null) block, so users will be null and you will get a NullReferenceException when executing this line:

users.Add(lineData);

You have to change this

List<string[]> users;

to this

List<string[]> users = new List<string[]>();
ekad
  • 14,436
  • 26
  • 44
  • 46