I have a method which takes in N, the number of objects I want to create, and I need to return a list of N objects.
Currently I can do this with a simple loop:
private static IEnumerable<MyObj> Create(int count, string foo) { var myList = new List<MyObj>(); for (var i = 0; i < count; i++) { myList .Add(new MyObj { bar = foo }); } return myList; }
And I'm wondering if there is another way, maybe with LINQ to create this list.
I've tried:
private static IEnumerable<MyObj> CreatePaxPriceTypes(int count, string foo) { var myList = new List<MyObj>(count); return myList.Select(x => x = new MyObj { bar = foo }); }
But this does seem to populate my list.
I tried changing the select to a foreach but its the same deal.
I realized that the list has the capacity of count and LINQ is not finding any elements to iterate.
myList.ForEach(x => x = new MyObj { bar = foo });
Is there a correct LINQ operator to use to get this to work? Or should I just stick with the loop?
You insert elements (objects) into a Java List using its add() method. Here is an example of adding elements to a Java List using the add() method: List<String> listA = new ArrayList<>(); listA. add("element 1"); listA.
We can create list of object in Python by appending class instances to list. By this, every index in the list can point to instance attributes and methods of the class and can access them. If you observe it closely, a list of objects behaves like an array of structures in C.
You can use the Range
to create a sequence:
return Enumerable.Range(0, count).Select(x => new MyObj { bar = foo });
If you want to create a List
, you'd have to ToList
it.
Mind you though, it's (arguably) a non-obvious solution, so don't throw out the iterative way of creating the list just yet.
You could create generic helper methods, like so:
// Func<int, T>: The int parameter will be the index of each element being created. public static IEnumerable<T> CreateSequence<T>(Func<int, T> elementCreator, int count) { if (elementCreator == null) throw new ArgumentNullException("elementCreator"); for (int i = 0; i < count; ++i) yield return (elementCreator(i)); } public static IEnumerable<T> CreateSequence<T>(Func<T> elementCreator, int count) { if (elementCreator == null) throw new ArgumentNullException("elementCreator"); for (int i = 0; i < count; ++i) yield return (elementCreator()); }
Then you could use them like this:
int count = 100; var strList = CreateSequence(index => index.ToString(), count).ToList(); string foo = "foo"; var myList = CreateSequence(() => new MyObj{ Bar = foo }, count).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With