简体   繁体   中英

string.contains and string.replace in one single line of code

I'm currently writing some software where I have to load a lot of columnnames from an external file. Usually I would do this with some JSON but for reasons of userfriendlyness I can't do it right now. I need to use a textfile which is readable to the users and includes a lot of comments.

So I have created my own file to hold all of these values.

Now when I'm importing these values in my software I essentially run through my configfile line by line and I check for every line if it matches a parameter which I then parse. But this way I end up with a big codeblock with very repetitive code and I was wondering is could not simplify it in a way so that every check is done in just one line.

Here is the code I'm currently using:

if (line.Contains("[myValue]"))
{
   myParameter = line.Replace("[myValue]", string.Empty).Trim();                        
}

I know that using Linq you can simply things and put them in one single line, I'm just not sure if it would work in this case?

Thanks for your help! Kenneth

Why not just create a method if this piece of code often repeated :

void SetParameter(string line, string name, ref string parameter)
{
    if (line.Contains(name))
    {
       parameter = line.Replace(name, string.Empty).Trim();                        
    }
}
SetParameter(line, "[myValue]", ref myParameter);

If you want to avoid calling both Replace and Contains , which is probably a good idea, you could also just call Replace :

void SetParameter(string line, string name, ref string parameter)
{
    var replaced = line.Replace(name, string.Empty);
    if (line != replaced)
    {
       parameter = replaced.Trim();                        
    }
}

Try this way (ternary):

myParameter = line.Contains("[myValue]")?line.Replace("[myValue]", string.Empty).Trim():myParameter;

Actually,

line.IndexOf should be faster.

From your code, look like you are replacing with just empty text, so why not take the entire string (consisting of many lines) and replace at one shot, instead of checking one line at a time.

You could use RegEx. This might possibly relieve you of some repetitive code

        string line = "[myvalue1] some string [someotherstring] [myvalue2]";
        // All your Keys stored at a single place
        string[] keylist = new string[] {  @"\[myvalue1]", @"\[myvalue2]" };

        var newString = Regex.Replace(line, string.Join("|", keylist), string.Empty);

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM