Is there a nice, efficient way to call the same method twice with two different arguments?

Let's say, for example, I have the following line:

var testString = "Hello, world";

And I want to call the following methods:

var newString = testString.Replace ("Hello", ") .Replace (" world "," ");

Is there some code construct that simplifies this so that I only need to specify the Replace method once and specify a sequence of parameters to navigate to it at a time?

+1


source to share


10 replies


Create a function that you pass String

and with Dictionary(String, String)

. Iterating over each element in the Dictionary and InputString.Replace(DictionaryEntry.Key, DictionaryEntry.Value)

. Return the string with the replaced values.



But I would just do .Replace.Replace

if it's only 2 times ...

+3


source


Another way to make it more readable is to add new lines and proper indentation (which would be better for me):



var newString = testString.Replace("Hello", "")
                          .Replace("world", "")
                          .Replace("and", "")
                          .Replace("something", "")
                          .Replace("else","");

      

+4


source


As noted in other posts, there are many ways.

But overall sweet = effective (= maintainable) = simple. It is probably best not to try unless there is a reason why you are describing the context of the question.

+2


source


Some languages โ€‹โ€‹(like python) have the concept of a shorten or collapse function, which is a functional way of representing loops over all the elements in a list.

Using shorthand you can write something like this

return reduce (lambda a, x: a.Replace (x, ''), ['hello', 'world'], initial)

which is the same as

a = initial
for x in ['hello', 'world']:
    a = a.Replace (x, '')
return a

In python, you can also pronounce it like

reduce (str.replace, ['hello', 'world'], initial).

Of course, it's easier, that's another question, but many people certainly love to write code like this.

+2


source


Any construct you come up with is likely to be more complex than your original post. If you have many different parameters to pass, you can build a vector of those arguments and iterate over it by making the call. But again, for your current example, the modified version will be longer and harder to write. Twice the repetition rate is too low.

+1


source


You can create your own Replace extension method that takes an IEnumberable parameter. Then go through the iterator and use the replace method.

Then you can call it like this: .Replace (newline [] {"Matt", "Joanne", "Robert"}, "")

I think this should do it

public static string Replace(this string s, IEnumerable<string> strings, string replacementstring)
{
    foreach (var s1 in strings)
    {
        s = s.Replace(s1, replacementstring);
    }

    return s;
}

      

+1


source


You can do this with a regular expression, for example:

var newString = Regex.Replace(testString, "Hello|world", "");

      

If you want to programmatically create a regular expression from a sequence, it would be something like this:

var stringsToReplace = new[] { "Hello", "world" };
var regexParts = stringsToReplace.Select(Regex.Escape);
var regexText = string.Join("|", regexParts.ToArray());

      

+1


source


I don't know if it's sweeter, but you can do:

string inputString = "Hello, world";
string newString = new[] { "Hello", "world" }.Aggregate(inputString, (result, replace) => result.Replace(replace, ""));

      

This will start with the input line as a seed and run the function with each line change.

The best example for understanding the Aggregate function might be:

List<Payment> payments = ...;
double newDebt = payments.Aggregate(oldDebt, (debt, payment) => debt - payment.Amount);

      

0


source


Many people say that you should use IEnumerable, List and Arrays, etc., and while this is perfectly "ok", I would rather use the params keyword in C # if you were you. IF I had to implement something like this, though, which I probably wouldn't want to do for something as simple as your Double Replace method calls ...

0


source


There are a few pitfalls I see with these patterns - first of all, strings that are immutable calls, replace multiple times or in a loop can be bad, especially if your input string is large. If you've lashed out on calling replace, then at least use the Replace method in the StringBuilder class.

0


source







All Articles