akohan
asked on
How to work with ArrayList in C#?
Hello group,
I'm reading a log file where I need 4 parameters from each line of it so I'm using ArrayList but the problem is that due to being new to C# I'm not sure if this works I just know how to create and add to an ArrayList so basically what I need is to know how to create a dynamic array, since the lines of log file are not defined and could change.
Any help is appreciated.
Regards,
ak
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Unless you are stuck with framework 1.1, you should not use ArrayList at all. You should use a strongly types List<T> instead.
As you have several values from each line, you can for example use a list of string arrays:
List<string[]> log = new List<string[]>();
foreach (string line in File.ReadAllLines("log.txt ")) {
log.Add(line.Split(' '));
}
Or you can create a class to represent a log line:
public class LogLine {
public string Param1 { get; private set; }
public string Param2 { get; private set; }
public string Param3 { get; private set; }
public string Param4 { get; private set; }
public LogLine(string line) {
string[] params = line.Split(' ');
Param1 = params[0];
Param2 = params[1];
Param3 = params[2];
Param4 = params[3];
}
}
The you use a list of LogLine objects:
List<LogLine> log = new List<LogLine>();
foreach (string line in File.ReadAllLines("log.txt ")) {
log.Add(new LogLine(line));
}
As you have several values from each line, you can for example use a list of string arrays:
List<string[]> log = new List<string[]>();
foreach (string line in File.ReadAllLines("log.txt
log.Add(line.Split(' '));
}
Or you can create a class to represent a log line:
public class LogLine {
public string Param1 { get; private set; }
public string Param2 { get; private set; }
public string Param3 { get; private set; }
public string Param4 { get; private set; }
public LogLine(string line) {
string[] params = line.Split(' ');
Param1 = params[0];
Param2 = params[1];
Param3 = params[2];
Param4 = params[3];
}
}
The you use a list of LogLine objects:
List<LogLine> log = new List<LogLine>();
foreach (string line in File.ReadAllLines("log.txt
log.Add(new LogLine(line));
}
ASKER
Thanks indeed.
regards,
ak