Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to refactor these 2 similar methods into one?
    primarykey
    data
    text
    <p>I've seen some samples of using 'T' to make a method reuseable for generic collections of different classes, but I've never really gotten into it or understood the samples. </p> <p>I wonder if it would be possible to put the 2 methods below into one and what the downsides of doing this would be (performance-wise).</p> <p>Anyone? </p> <pre><code> [NonAction] public List&lt;SelectListItem&gt; ToSelectList(IEnumerable&lt;Department&gt; departments, string defaultOption) { var items = departments.Select(d =&gt; new SelectListItem() { Text = d.Code + " - " + d.Description, Value = d.Id.ToString() }).ToList(); items.Insert(0, new SelectListItem() { Text = defaultOption, Value = "-1" }); return items; } [NonAction] public List&lt;SelectListItem&gt; ToSelectList(IEnumerable&lt;Function&gt; functions, string defaultOption) { var items = functions.Select(f =&gt; new SelectListItem() { Text = f.Description, Value = f.Id.ToString() }).ToList(); items.Insert(0, new SelectListItem() { Text = defaultOption, Value = "-1" }); return items; } </code></pre> <hr> <p><strong>SOLUTION</strong></p> <p>The solution that I used:</p> <p><em>usage</em></p> <pre><code>var departmentItems = departments.ToSelectList(d =&gt; d.Code + " - " + d.Description, d =&gt; d.Id.ToString(), " - "); var functionItems = customerFunctions.ToSelectList(f =&gt; f.Description, f =&gt; f.Id.ToString(), " - "); </code></pre> <p><em>with</em></p> <pre><code> public static class MCVExtentions { public static List&lt;SelectListItem&gt; ToSelectList&lt;T&gt;(this IEnumerable&lt;T&gt; enumerable, Func&lt;T, string&gt; text, Func&lt;T, string&gt; value, string defaultOption) { var items = enumerable.Select(f =&gt; new SelectListItem() { Text = text(f), Value = value(f) }).ToList(); items.Insert(0, new SelectListItem() { Text = defaultOption, Value = "-1" }); return items; } } </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.
 

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