I have some code that reads a text file and sets it to a string. Each line of the text file contains separate data parameters that I a trying to extract. Here is an small ex
Assuming the text file is in the format posted and only contains the data parameters, an alternative approach would be to read the contents of the file and project the contents into a dictionary since you already know the parameter names, i.e,. "part", "quantity", etc...
Dictionary<string, string> param = File
.ReadLines("path.to.file.txt")
.Select(x => x.Split('='))
.ToDictionary(x => x[0], y => y[1]);
The contents can then be accessed by the key name, similar to how you were originally assigning the variables:
string partNum = param["part"];
Or, just use the dictionary as needed without assigning to a local variable.
You can use split, it can be easier to read:
string value = partData.Split('=', 2)[1];
Beware that can throw an exception if there's no '=' on the line.
This will be more robust if you use
var parts = string.Split('=')
Who knows if someone decides to put a space before or after the equal sign? That would break your existing solution because it would not find "part =XXX". With split you get the parts on either side.
You can also use a regex to do this; it can handle more complex cases than the simple IndexOf
or Split
solutions, such as skipping whitespaces around the =
or not match certain patterns, or extract all the components found in a single line at once.
string partNum = Regex.Match(partData, @"=(.*)$", RegexOptions.Multiline).Groups[1].Value;
The regex will be slower for the simple case (such as just splitting on the =
), but if you actually want to process and extract data from a halfway complex pattern it will be more efficient and more concise as well.
Also, by checking the Success
property on the match, you could validate that the data is conforming to the expected pattern along the way without requiring any additional processing/verification logic.
Here's an example which extracts the parts before and after the = sign for each text line which is using the expected pattern in the string, and trims the parts along the way:
for (Match match = Regex.Match(partData, @"^\s*([^=]+?)\s*=\s*(.*?)\s*$", RegexOptions.Multiline);
match.Success;
match = match.NextMatch()) {
// this code runs for each line in your string which has the expected pattern
string key = match.Groups[1].Value;
string value = match.Groups[2].Value;
}
Edit: Here's a fiddle which does show how this code works with your sample data.
Yes, you can do it much more concisely.
string partNum = partData.Substring(partData.IndexOf("=") + 1);
This uses the overloaded version of String.Substring that only accepts one parameter, the starting position in the string. It continues from that point to the end of the string.
Clearly this only works if you're certain that there is equals sign in your partData
, but so would the original code you posted.