Reputation: 21184
Below is how far I made it. I need to send Expression<Func<T, string>>
as the parameter instead of Func<T,string>
to the Get function, and still have Select() work. Is this easily possible? This is formatted for LinqPad.
void Main()
{
// Setup sample data in wholelist
var wholelist = new List<Example>();
for (var a = 0; a < 10; a++)
{ var t = new Example { id = a.ToString(), name = a.ToString() };
wholelist.Add(t);
}
// Do the real work
var names = Get<Example>( wholelist, p => p.name );
// LinqPad shows content
names.Dump();
}
public class Example
{
public string id {get;set;}
public string name {get;set;}
}
public static List<string>
Get<T>(IEnumerable<T> source, Func<T, string> selector)
{
var list = source.Select<T,string>(selector).ToList();
return list;
}
The why is because we have a lot of functions already calling this one with Expression<Func<T,string>>
.
Upvotes: 0
Views: 1124
Reputation: 2999
Have you tried expression.Compile?
public static List<string> Get<T>(IEnumerable<T> source, Expression<Func<T, string>> selector)
{
var list = source.Select<T, string>(selector.Compile()).ToList();
return list;
}
Upvotes: 2