HoopSnake
HoopSnake

Reputation: 736

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

Is it possible to create a func<> or lamda method to achieve this type of result

 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

So for the single item 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

Upvotes: 1

Views: 567

Answers (3)

dthorpe
dthorpe

Reputation: 36082

IEnumerable<item> myfunc(IEnumerable<string> stringlist)
{
    var q = from s in stringlist
            select new item(s);
    return q.ToList();
}

Upvotes: 3

David Ruttka
David Ruttka

Reputation: 14409

Are you just trying to "reshape" the IList<string> as IList<item>?

IList<string> listOfStrings = new string[] {  "bob","mary"};
IList<item> listOfItems = listOfStrings.Select(s => new item(s)).ToList();

Upvotes: 5

BrokenGlass
BrokenGlass

Reputation: 160942

You will have to use a Select projection instead of ForEach and then convert the resulting IEnumerable<item> to a list using ToList() - this should work:

Func<IEnumerable<string>,IList<item>> func2 = x => x.Select( i => new item(i)).ToList();

Upvotes: 4

Related Questions