0

我正在尝试读取 .csv 文件,进行一些格式化,将每行拆分为其列数据并将新的分隔列数据数组添加到数组列表中。然后我想以不同的方式对列表进行排序。目前只是按用户名按字母顺序升序。

这是我到目前为止所尝试的:

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

这给出了一个错误:

使用未分配的局部变量“用户”

我不明白为什么它说它是一个未分配的变量?为什么我在 Visual Studios 2010 中运行程序时列表不显示?

4

3 回答 3

5

因为对象需要在使用之前创建,构造函数设置对象,准备使用这个为什么你会得到这个错误

使用这样的东西

List<string[]> users = new List<string[]>() ; 
于 2014-02-13T11:26:53.810 回答
1

利用 :

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

代替 :

List<string[]> users;
于 2014-02-13T11:27:35.390 回答
1

Visual Studio 给了您Use of unassigned local variable 'users'错误,因为您声明了users变量,但您从未在while((line = file.ReadLine()) != null)块之前为其分配任何值,因此将为 null 并且在执行此行时users您将收到NullReferenceException :

users.Add(lineData);

你必须改变这个

List<string[]> users;

对此

List<string[]> users = new List<string[]>();
于 2014-02-13T11:39:12.937 回答