Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method chaining on list with condition

Tags:

c#

.net

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?

like image 542
Noobnewbier Avatar asked Oct 20 '25 04:10

Noobnewbier


2 Answers

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;
like image 84
Maxim Kosov Avatar answered Oct 21 '25 16:10

Maxim Kosov


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));

like image 24
Alvin Sartor Avatar answered Oct 21 '25 17:10

Alvin Sartor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!