Reputation: 1038
I've a list of strings.
List<string> myData = new List<string>
{
"abcdefghi1",
"abcdefghi2"
"abcdefghi3"
};
If I manually made the following LINQ, it works perfectly.
var myObjectList = (from s in myData
select new myObject
{
Prop1 = s.Substring(0,3),
Prop2 = s.Substring(4,1)...
}).ToList();
When I check the "select new myObject" type, it's a Func<string, T>
.
If I create the follow method
List<T> getMyObjects(List<string> myData, Func<string, T> selector) where T : class
{
return (from s in myData select selector).ToList();
}
And call it like
var myObjectList = getMyObjects(data,
value => new myObject
{
Prop1 = value.Substring(0,3),
Prop2 = value.Substring(4,1)
});
It returns a list of {System.Func<string, MyObject>}
instead of a list of
Any idea on how to accomplish that ?
Br,
Upvotes: 0
Views: 60
Reputation: 9704
You're selecting the mapping function instead of the result of using it to map.
List<T> getMyObjects(List<string> myData, Func<string, T> selector) where T : class
{
return (from s in myData select selector).ToList();
}
should likely be
List<T> getMyObjects(List<string> myData, Func<string, T> selector) where T : class
{
return (from s in myData select selector(s)).ToList();
// ^^^ get the result of your selector delegate against the string.
}
Which, as @Camilo Terevinto points out, can be further simplified to:
List<T> getMyObjects(List<string> myData, Func<string, T> selector) where T : class
{
return myData.Select(selector).ToList();
}
Upvotes: 2