Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you're looking to <em>conditionally</em> project a Foo to another Foo (leaving others untouched), you can do something like:</p> <pre><code>IEnumerable&lt;Foo&gt; foos = ... var transformed = foos.Select(foo =&gt; myCondition(foo) ? transform(foo) : foo); </code></pre> <p>On the other hand, if you only want to project Foos that match the condition:</p> <pre><code>var transformed = foos.Where(foo =&gt; myCondition(foo)) .Select(foo =&gt; transform(foo)); </code></pre> <p>Do note that both of these return <em>new</em> sequences - LINQ isn't normally used to <em>modify</em> existing collections. You could of course materialize the results into a collection, overwriting an existing variable if necessary.</p> <pre><code>// assuming the transform is from Foo -&gt; Foo foos = foos.Select(foo =&gt; transform(foo)).ToList(); </code></pre> <p>Since you specifically mention <em>lists</em>, there is another non-LINQ immediate-execution alternative to the first query - the <a href="http://msdn.microsoft.com/en-us/library/73fe8cwf.aspx" rel="noreferrer"><strong><code>List&lt;T&gt;.ConvertAll</code></strong></a> method:</p> <pre><code>List&lt;Foo&gt; foos = ... // implicitly List&lt;Foo&gt; assuming the transform is from Foo -&gt; Foo var transformed = foos.ConvertAll (foo =&gt; myCondition(foo) ? transform(foo) : foo); </code></pre> <hr> <p><strong>EDIT</strong>: Sounds like you're looking for a "ReplaceWhere" method - as far as I know, there is no <em>direct</em> framework method that replaces the elements of a list based on a predicate. It's easy to write one yourself though:</p> <pre><code>/// &lt;summary&gt; /// Replaces items in a list that match the specified predicate, /// based on the specified selector. /// &lt;/summary&gt; public static void ReplaceWhere&lt;T&gt;(this IList&lt;T&gt; list, Func&lt;T, bool&gt; predicate, Func&lt;T, T&gt; selector) { // null-checks here. for (int i = 0; i &lt; list.Count; i++) { T item = list[i]; if (predicate(item)) list[i] = selector(item); } } </code></pre> <p><strong>Usage</strong>:</p> <pre><code>List&lt;int&gt; myList = ... myList.ReplaceWhere(i =&gt; i &gt; 0, i =&gt; i * i); </code></pre>
 

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