我有一个字符串列表。
List<string> myData = new List<string>
{
"abcdefghi1",
"abcdefghi2"
"abcdefghi3"
};
如果我手动制作以下LINQ,则效果很好。
var myObjectList = (from s in myData
select new myObject
{
Prop1 = s.Substring(0,3),
Prop2 = s.Substring(4,1)...
}).ToList();
当我检查“选择新的myObject”类型时,它是Func<string, T>
。
如果我创建关注方法
List<T> getMyObjects(List<string> myData, Func<string, T> selector) where T : class
{
return (from s in myData select selector).ToList();
}
像这样称呼
var myObjectList = getMyObjects(data,
value => new myObject
{
Prop1 = value.Substring(0,3),
Prop2 = value.Substring(4,1)
});
它返回{System.Func<string, MyObject>}
的列表,而不是
关于如何实现这一目标的任何想法?
Br,
答案 0 :(得分:2)
您正在选择映射功能,而不是使用它来映射的结果。
List<T> getMyObjects(List<string> myData, Func<string, T> selector) where T : class
{
return (from s in myData select selector).ToList();
}
应该是
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.
}
@Camilo Terevinto指出,可以进一步简化为:
List<T> getMyObjects(List<string> myData, Func<string, T> selector) where T : class
{
return myData.Select(selector).ToList();
}