我正在编写一个简单的代码来从文本文件中读取一些数据并存储在C#列表中,但是存在问题.如果问题出在我身边或是图书馆,请提供帮助.我写了以下函数:
public List<EmpBO> ReadData()
{
EmpBO temp = new EmpBO();
List<EmpBO> lis = new List<EmpBO>(100);
string[] tokens;
string data;
StreamReader sw = new StreamReader(new FileStream("emp.txt",FileMode.OpenOrCreate));
int ind = 0;
while ((data = sw.ReadLine())!=null)
{
Console.WriteLine("Reading " + data);
tokens = data.Split(';');
temp.Id = int.Parse(tokens[0]);
temp.Name = tokens[1];
temp.Salary = double.Parse(tokens[2]);
temp.Br = double.Parse(tokens[3]);
temp.Tax = double.Parse(tokens[4]);
temp.Designation = tokens[5];
//lis.Add(temp);
lis.Insert(ind,temp);
ind++;
}
sw.Close();
Console.WriteLine("Read this material and returning list");
for (int i = 0; i < lis.Count; i++)
{
Console.WriteLine("" + (lis.ElementAt(i)).Name);
}
//foreach (EmpBO ob in lis)
//{
// Console.WriteLine("" + ob.Id + ob.Name);
//}
return lis;
}
Run Code Online (Sandbox Code Playgroud)
文件emp.txt包含:
1; Ahmed; 100000; 20; 1000;经理
2; Bilal; 200000; 15; 2000; ceo
现在你可以看到在while循环中,我已经显示了StreamReader读取的内容,在这种情况下它会进行2次迭代并显示.
阅读1; Ahmed; 100000; 20; 1000;经理
阅读2; Bilal; 200000; 15; 2000; ceo
正如您所见,我将此信息保存在temp中并插入列表中.
在while循环结束后,当我遍历列表以了解存储在其中的内容时,它会显示:
阅读此材料并返回
Bilal
BIlal 列表
好吧,第二条记录存储在列表中两次,第一条记录不存在.这似乎是什么问题?我也使用了Add()方法,并且foreach循环用于遍历列表,因为你可以看到它被注释掉但是结果是相同的..请帮忙
移动这一行
EmpBO temp = new EmpBO();
Run Code Online (Sandbox Code Playgroud)
进入while循环使它看起来像
while ((data = sw.ReadLine())!=null){
EmpBO temp = new EmpBO();
Console.WriteLine("Reading " + data);
tokens = data.Split(';');
temp.Id = int.Parse(tokens[0]);
temp.Name = tokens[1];
temp.Salary = double.Parse(tokens[2]);
temp.Br = double.Parse(tokens[3]);
temp.Tax = double.Parse(tokens[4]);
temp.Designation = tokens[5];
//lis.Add(temp);
lis.Insert(ind,temp);
ind++;
}
Run Code Online (Sandbox Code Playgroud)
您不是EmpBO
为每个条目创建新的,而是使用读取值覆盖同一对象并将其再次添加到List中.
效果是您将相同的对象多次添加到List.