简体   繁体   English

使用Lambda和Func <>的动态构造函数

[英]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.

相关问题 Lambda可在FindAll中使用,但不能用作Func(或Expression)使用 - Lambda works in FindAll, but not when using it as an Func (or Expression) 使用Func传递lambda表达式的多个条件 - Multiple conditions on lambda expression to pass using Func 使用Func &lt;&gt;而不是lambda时,超时已过期 - Timeout expired when using a Func<> instead of a lambda 在表达式中使用 generics <func<mytype, torderby> > 在构造函数中</func<mytype,> - Using generics in an Expression<Func<MyType, TOrderBy>> in a Constructor 基于lambda表达式功能查询DocumentDB <TEntity, dynamic> - Query DocumentDB based on lambda expression func<TEntity, dynamic> Lambda表达式,用于使用表达式查询KeyValuePairs数组 <Func<T, bool> &gt; - Lambda expression for querying an array of KeyValuePairs using Expression<Func<T, bool>> 当构造函数使用Func具有依赖项时,Moq CreateInstance失败<T> - Moq CreateInstance fails when constructor has dependencies using Func<T> 使用 Moq 模拟 Func&lt;&gt; 构造函数参数并验证它被调用了两次 - Using Moq to Mock a Func<> constructor parameter and Verify it was called twice 使用Reflection Emit创建构造函数调用,该函数将Func &lt;&gt;作为参数传递 - Create a constructor call using Reflection Emit that passes a Func<> as a parameter Lambda Func &lt;&gt;和Fluent - Lambda Func<> and Fluent
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM