我正在开发一个小程序,它基本上从txt读取多个数组并将它们写入另一个文件,但另外,它应该生成一个唯一的数字并将它放在信息之前。我的第一部分工作没有问题,但第二部分导致我的问题,即使它应该工作。
public static void Main(string[] args)
{
StreamReader vehiclereader = new StreamReader(@"C:\Users\Admin\Desktop\Program\vehicles.txt");
string line = vehiclereader.ReadToEnd();
string ID;
string category;
string Type;
string Brand;
string Model;
string Year;
string Colour;
while (line != null)
{
var parts = line.Split(',');
Type = parts[0];
Brand = parts[1];
Model = parts[2];
Year = parts[3];
Colour = parts[4];
Console.WriteLine(line);
string[] lines = { line };
System.IO.File.WriteAllLines(@"C:\Users\Admin\Desktop\Program\vehicles2.txt", lines);
List<string> categories = new List<string>();
categories.Add(Type);
int count = categories.Where(x => x.Equals(Type)).Count();
ID = Type.Substring(0, 4) + count.ToString("00");
Console.ReadKey();
}
}
}
目前,此代码从txt文件中读取,将其显示在控制台中并将其写回另一个txt文件。这很好,不愿意工作的部分是唯一的数字生成器。
最后5行代码应该在&#39; Type&#39;之前添加一个唯一的数字。数据总是从001开始。如果&#39; Type&#39;数据是相同的,然后数字按升序增长。否则,应为新类型重置唯一编号,并从001开始计数,并且对于相同类型应保持增长。 (例如,对于所有轻型车辆,计数器应该是相同的,对于重型车辆,计数器应该是不同的,但计算所有重型车辆)
我愿意接受任何帮助或建议!
答案 0 :(得分:0)
此代码存在各种问题和建议,允许我在提供更正版本之前列出它们:
我创建了一个负责计数的课程,以展示如何“分离关注点”。
显然我没有你的文件,所以我不知道这是否有用。
class Program
{
public static void Main(string[] args)
{
var typeCounter = new TypeCounter();
using (StreamWriter vehicleWriter = new StreamWriter(@"C:\Users\Admin\Desktop\Program\vehicles2.txt"))
using (StreamReader vehicleReader = new StreamReader(@"C:\Users\Admin\Desktop\Program\vehicles.txt"))
{
string line;
while ((line = vehicleReader.ReadLine()) != null)
{
var parts = line.Split(',');
string type = parts[0].Substring(0, 4); // not sure why you're using substring, I'm just matching what you did
var identifier = typeCounter.GetIdentifier(type);
vehicleWriter.WriteLine($"{identifier},{line}");
}
}
Console.ReadKey();
}
}
public class TypeCounter
{
private IDictionary<string, int> _typeCount = new Dictionary<string, int>();
public string GetIdentifier(string type)
{
int number;
if (_typeCount.ContainsKey(type))
{
number = ++_typeCount[type];
}
else
{
number = 1;
_typeCount.Add(type, number);
}
return $"{type}{number:00}"; // feel free to use more zeros
}
}