我正在尝试读取.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);
这会产生一个错误:
使用未分配的本地变量'users'
我不明白为什么说这是一个未分配的变量?为什么在Visual Studio 2010中运行程序时,列表不显示?
答案 0 :(得分:5)
因为在使用之前需要创建对象,所以构造函数设置对象,准备好使用这个为什么会出现此错误
使用类似的东西
List<string[]> users = new List<string[]>() ;
答案 1 :(得分:1)
使用:
List<string[]> users= new List<string[]>();
而不是:
List<string[]> users;
答案 2 :(得分:1)
Visual Studio为您提供了Use of unassigned local variable 'users'
错误,因为您声明了users
变量,但在while((line = file.ReadLine()) != null)
阻止之前从未为其分配任何值,因此users
将为空,您将执行此行时获得NullReferenceException:
users.Add(lineData);
你必须改变这个
List<string[]> users;
到这个
List<string[]> users = new List<string[]>();