C
C#4w ago
Luna

✅Refactor C# code

guys my code works, but i'm doubting that i made the most performant way to do it
public struct Proc
{
public string Name;
public int ID;
public string? Owner;
}
....................
public static void SaveAppsList()
{
if (File.Exists(FILE_PATH)) File.Delete(FILE_PATH);

using StreamWriter writer = new(FILE_PATH);
foreach (Proc item in ListOfProcs)
writer.WriteLine($"{item.ID}^{item.Name}^{item.Owner}");
}
public static void LoadAppsList()
{
if (!File.Exists(FILE_PATH)) return;
string readText = File.ReadAllText(FILE_PATH);

if (readText.Trim() == string.Empty) return;

readText = readText.Replace("\r\n", "\n");
List<string> lines = [.. readText.Split('\n')];
foreach (string line in lines)
{
if (line.Trim() == string.Empty) continue;
string[] processInfo = line.Split('^');
Proc proc = new()
{
ID = int.Parse(processInfo[0]),
Name = processInfo[1],
Owner = processInfo[2]
};
ListOfProcs.Add(proc);
}
}
public struct Proc
{
public string Name;
public int ID;
public string? Owner;
}
....................
public static void SaveAppsList()
{
if (File.Exists(FILE_PATH)) File.Delete(FILE_PATH);

using StreamWriter writer = new(FILE_PATH);
foreach (Proc item in ListOfProcs)
writer.WriteLine($"{item.ID}^{item.Name}^{item.Owner}");
}
public static void LoadAppsList()
{
if (!File.Exists(FILE_PATH)) return;
string readText = File.ReadAllText(FILE_PATH);

if (readText.Trim() == string.Empty) return;

readText = readText.Replace("\r\n", "\n");
List<string> lines = [.. readText.Split('\n')];
foreach (string line in lines)
{
if (line.Trim() == string.Empty) continue;
string[] processInfo = line.Split('^');
Proc proc = new()
{
ID = int.Parse(processInfo[0]),
Name = processInfo[1],
Owner = processInfo[2]
};
ListOfProcs.Add(proc);
}
}
btw, i hate my own code, i know i can do better, but idk how
6 Replies
Angius
Angius4w ago
There are some things that could be improved, sure. For example, no need to spread the results of a split into a list, just use it as-is No need to do the replacing of \r\n either, you can trim each line, with string split options Similarly, you can ensure you only get non-empty lines
var lines = readText.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.Trim)
var lines = readText.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.Trim)
off the top of my head
Luna
Luna4w ago
okay, thx lemme try worked, i got another bug, but that is on me lol is there a way to work is CSV files? so i don't need to make manually like I am doing rn
Luna
Luna4w ago
thxxx
leowest
leowest4w ago
$close
MODiX
MODiX4w ago
If you have no further questions, please use /close to mark the forum thread as answered