var someList = otherList.ReplaceAll(foo, bar);
if (someCondition)
{
someList = someList.ReplaceAll(someOtherFoo, someOtherBar);
}
In my code, I am having the above code snippet, I find the if
statement very annoying and would like to do something like this instead:
var someList = otherList
.ReplaceAll(foo, bar)
.Given(someCondition)
.ReplaceAll(someOtherFoo, someOtherBar);
such that ReplaceAll(someOtherFoo, someOtherBar)
is only executed when someCondition
is true
.
Is that possible?
While you can indeed create an extension as suggested by others, I wouldn't do that in actual production code because it's defeats the purpose of Linq.
Linq is functional and good for processing sequences or streams. Each Linq chaining operator processes incoming data and transforms it to another data. Given
extension you are looking for is procedural and doesn't do anything with the sequence.
Given
also doesn't support lazy evaluation which is one of the features of Linq.
By introducing such extension you just making the code harder to read for the next person working on this code.
By contrast, good old if
can be easily understood by everyone.
If you want to save couple of lines you can use ternary operator:
var someList = otherList.ReplaceAll(foo, bar);
someList = someCondition ? someList.ReplaceAll(someOtherFoo, someOtherBar) : someList;
Why don't you create an extension?
public static List<T> ExecuteIf<T>(
this List<T> list,
Func<bool> condition,
Func<List<T>, List<T>> action)
{
return condition() ? action(list) : list;
}
var someList = otherList
.ReplaceAll(foo, bar)
.ExecuteIf(() => someCondition, (l) => l.ReplaceAll(someOtherFoo, someOtherBar));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With