[英]Dynamic Constructor using Lambda and Func<>
I have a multithreaded app that is creating a list of strings on a BlockingCollection queue, I want to take that list of strings and convert it to a collection of item objects in one or 2 steps 我有一个多线程应用程序,它正在BlockingCollection队列上创建一个字符串列表,我想采用该字符串列表,并通过一两个步骤将其转换为项目对象的集合。
Is it possible to create a func<> or lamda method to achieve this type of result 是否可以创建func <>或lamda方法来实现这种类型的结果
public class item
{
public string name { get; set; }
public item(string nam)
{
name = nam;
}
}
IList<string> alist = new string[] { "bob","mary"};
Where you take a Ilist<> or IEnumerable<> of type string and return IList 在您获取字符串类型的Ilist <>或IEnumerable <>并返回IList的地方
So for the single item Func<> 因此对于单项Func <>
Func<string, item> func1 = x => new item(x);
But essetially the signiture would look like 但实际上签名看起来像
Func<IEnumerable<string>,IList<item>> func2 = x=> x.ForEach(i => func1(i));
Am I trying to put a round peg in sqaure hole or is my syntax/logic just wrong 我是要在方孔中钉一个圆钉还是语法/逻辑错误
Thanks in advance 提前致谢
Are you just trying to "reshape" the IList<string>
as IList<item>
? 您是否只是想将IList<string>
“重塑”为IList<item>
?
IList<string> listOfStrings = new string[] { "bob","mary"};
IList<item> listOfItems = listOfStrings.Select(s => new item(s)).ToList();
您将必须使用Select
投影而不是ForEach
,然后使用ToList()
将生成的IEnumerable<item>
转换为列表-这应该起作用:
Func<IEnumerable<string>,IList<item>> func2 = x => x.Select( i => new item(i)).ToList();
IEnumerable<item> myfunc(IEnumerable<string> stringlist)
{
var q = from s in stringlist
select new item(s);
return q.ToList();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.