Reputation: 1189
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:
public T Get<T>(string id, Func<T> 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 => new CustomType { id = x.id, name = x.name }).ToList());
}
return item;
}
void doSomethingElse(List<CustomType> custom)
{
....
}
Leme show how I cam currently calling this perhaps that will help:
public List<MyDataSet> GetData(string keywords, string id)
{
return _myObject.Get(
id,
() => db.GetDataSet(keywords, id).ToList());
// Perhaps I could add another parameter here to
// handled the projection ????
}
Thanks to Reed I figured it out...would look like this:
public T Get<T>(string id, Func<T> getItemCallback, Func<T, List<CustomType>> selector) where T : class
{
item = getItemCallback();
if (item != null)
{
doSomething(item);
var custom = selector(item);
if (custom != null)
{
doSomethingElse(custom);
}
}
return item;
}
And The call looks like:
public List<MyDataSet> GetData(string keywords, string id)
{
return _myObject.Get(
id,
() => db.GetDataSet(keywords, id).ToList(),
x => x.Select(d => new CustomType { id = d.ReferenceId, name = d.Name })
.ToList());
}
Upvotes: 1
Views: 1169
Reputation: 564691
You would need to also pass in a conversion function:
public T Get<T>(string id, Func<T> getItemCallback, Func<T, List<CustomType>> conversion) where T : class
{
item = getItemCallback();
if (item != null)
{
doSomeThing(item);
if (conversion != null)
doSomethingElse(conversion(item));
}
return item;
}
Upvotes: 2