Search code examples
c#.netlinqanonymous-methods

Is it possible to have an anonymous method when creating a list of items, with .NET + Linq?


i'm trying to do the following, but not sure how ...

var foo = new Foo
    {
        Id = MyRandom<int>(1, 100),
        Name = MyRandom<string>(5,20),
        MyPets = MyRandom<bool>() ?
            new IList<Pet>
            (petList =>
                { 
                   var x = MyRandom<int>(1, 4);
                   for (int i = 0; i < x; i++)
                   {
                       petList.Add(new Pet(MyRandom<string>(1,15));
                   }
                }
            : null
    };

so .. this creates a random list of pets.

Any ideas?


Solution

  • No.

    Instead, you can create a lambda expression, then call it immediately:

    MyRandom<bool>() ? null : (new Func<IList<Pet>>(() => { return ... })()