Note that there are some explanatory texts on larger screens.

plurals
  1. POc# lambda expression - add delegate results to generic list
    primarykey
    data
    text
    <p><strong>Question:</strong> I have just wrote my first code using c# lambda expressions. It works, but I am not sure if this is the best way to do it. Any recommendations on a better way to do the lambda expression? It seems odd to have numerous lines of code in the expression like I do below.</p> <p><strong>Background:</strong> I have a generic list of delegates. Each delegate function returns an enum value indicating what happened in the function. Upon evaluation of the delegate, I need to add the enum to a List if it was not a specific enum value.</p> <p><strong>Disclaimer:</strong> Code here is very generic, the real code actually does stuff in the delegates to determine the return value!</p> <hr> <pre><code>class Class1 { public enum WhatHappened { ThingA, ThingB, Nothing } private delegate WhatHappened del(); public static List&lt;WhatHappened&gt; DoStuff() { List&lt;del&gt; CheckValues = new List&lt;del&gt;(); List&lt;WhatHappened&gt; returnValue = new List&lt;WhatHappened&gt; { }; CheckValues.Add(delegate { return method1(); }); CheckValues.Add(delegate { return method2(); }); CheckValues.ForEach(x =&gt; { WhatHappened wh = x(); if (wh != WhatHappened.Nothing) returnValue.Add(wh); }); return returnValue; } private static WhatHappened method1() { return WhatHappened.Nothing; } private static WhatHappened method2() { return WhatHappened.ThingA; } } </code></pre> <p><strong>Note:</strong> I originally had the lambda like adding all the items (see below), then removing the ones I didn't want (WhatHappened.Nothing).</p> <pre><code>CheckValues.ForEach(x =&gt; returnValue.Add(x())); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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