Method that assigns a value to a variable in all classes in a list

Let’s say you want a list of ten of those Object (unfortunately named) class instances in a list, and you want them all to have the a property set to “Foo”. You can use Enumerable.Range to create an enumeration with ten elements, then Select to create the objects. When creating the object, you can initialize the a property using initializer syntax. Once they are created you can create the list with ToList.

Technically this is one line of code although for readability it may be a good idea to span it across a few visual lines.

List<Object> myList = Enumerable
        i => new Object { a = "Foo" }

Browse More Popular Posts

Leave a Comment