Note that there are some explanatory texts on larger screens.

plurals
  1. POPipe forwards in C#
    primarykey
    data
    text
    <p>Continuing <a href="https://stackoverflow.com/questions/308481/writing-the-f-recursive-folder-visitor-in-c-seq-vs-ienumerable">my investigation</a> of expressing F# ideas in C#, I wanted a pipe forward operator. For anything wrapped in a IEnumerable, we already have it, as you can .NextFunc() to your heart's content. But for example if you have any fold-like reduction at the end, you can't feed the result of that into a function.</p> <p>Here are two extension methods, I wondered if anyone else had tried this, and if it's a good idea or not (EDIT: now with <a href="http://#337846" rel="nofollow noreferrer">Earwicker's Maybe</a> included):</p> <pre><code>public static void Pipe&lt;T&gt;(this T val, Action&lt;T&gt; action) where T : class { if (val!=null) action(val); } public static R Pipe&lt;T, R&gt;(this T val, Func&lt;T, R&gt; func) where T : class where R : class { return val!=null?func(val):null; } </code></pre> <p>You can then write something like: </p> <pre><code>Func&lt;string, string[]&gt; readlines = (f) =&gt; File.ReadAllLines(f); Action&lt;string, string&gt; writefile = (f, s) =&gt; File.WriteAllText(f, s); Action&lt;string, string&gt; RemoveLinesContaining = (file, text) =&gt; { file.Pipe(readlines) .Filter(s =&gt; !s.Contains(text)) .Fold((val, sb) =&gt; sb.AppendLine(val), new StringBuilder()) .Pipe((o) =&gt; o.ToString()) .Pipe((s) =&gt; writefile(file, s)); }; </code></pre> <p>(I know, Filter == Where in C#, and Fold==Aggregate, but I wanted to roll my own, and I could have done WriteAllLines, but that's not the point)</p> <p>EDIT: corrections as per Earwicker's comment (if I've understood correctly).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload