C# Substring Alternative - Return rest of line within string after character

前端 未结 5 565
离开以前
离开以前 2021-01-17 03:25

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

5条回答
  •  清酒与你
    2021-01-17 04:06

    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 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.

提交回复
热议问题