0

我试图读取一个.csv文件,做一些格式化,将每一行分割成它的列数据并将新的分离列数据数组添加到数组列表中。然后我想用不同的方式排列列表。目前仅通过用户名按字母顺序升序。尝试使用C#中的IOrderedEnumerable命令列表

这是我迄今为止尝试:

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

这给了一个错误:

Use of unassigned local variable 'users'

我不明白为什么它说这是一个未赋值的变量?为什么当我在Visual Studio 2010中运行程序时,列表不显示?

回答

5

因为对象需要在使用前要创建,构造函数设置的对象,就可以使用这就是你得到这个错误

使用这样的事情

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

用途:

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

List<string[]> users; 
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[]>(); 
相关问题