Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do you create a dynamic select projection from a generic using Linq in C#?
    primarykey
    data
    text
    <p>So I have a function that I pass Func call back to. I would also like to add some sort of selection projection to be able to do the projection on the object, meaning I would only perform one database call. The function looks something like this:</p> <pre><code>public T Get&lt;T&gt;(string id, Func&lt;T&gt; getItemCallback) where T : class { item = getItemCallback(); if (item != null) { doSomeThing(item); // Here I would like to call something else that is // expecting a specific type. Is there way to pass in a // dynamic selector? doSomethingElse(item.Select(x =&gt; new CustomType { id = x.id, name = x.name }).ToList()); } return item; } void doSomethingElse(List&lt;CustomType&gt; custom) { .... } </code></pre> <p>Leme show how I cam currently calling this perhaps that will help:</p> <pre><code>public List&lt;MyDataSet&gt; GetData(string keywords, string id) { return _myObject.Get( id, () =&gt; db.GetDataSet(keywords, id).ToList()); // Perhaps I could add another parameter here to // handled the projection ???? } </code></pre> <p>Thanks to Reed I figured it out...would look like this:</p> <pre><code>public T Get&lt;T&gt;(string id, Func&lt;T&gt; getItemCallback, Func&lt;T, List&lt;CustomType&gt;&gt; selector) where T : class { item = getItemCallback(); if (item != null) { doSomething(item); var custom = selector(item); if (custom != null) { doSomethingElse(custom); } } return item; } </code></pre> <p>And The call looks like:</p> <pre><code> public List&lt;MyDataSet&gt; GetData(string keywords, string id) { return _myObject.Get( id, () =&gt; db.GetDataSet(keywords, id).ToList(), x =&gt; x.Select(d =&gt; new CustomType { id = d.ReferenceId, name = d.Name }) .ToList()); } </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