I'm looking for a way to initialize a variable of type List with a set of values (in C#). Yes, there is object initialization but that requires a new object for each value you want and I would rather avoid it.
Here's a sample:
class MyObject
{
public string Name {get;set;}
}
List<MyObject> OldNames = new List<MyObject>(10);
List<MyObject> NewNames = new List<MyObject>(5);
This is fine and dandy but OldNames contains 10 null references to an object of type MyObject.
Using a list initializer I could do this:
List<MyObject> OldNames = new List<MyObject>{
new MyObject(),
new MyObject(),
new MyObject(),
etc.
That's kind of a pain as I have many list variables and various sizes to initialize (for exaample one variable is a list of 26 objects. Yes, I could write a function or maybe extension to do this initialization for me (in a loop where I provide the size) but again that's code I don't necessarily want to write.
I'm hoping there's some kind of lamdba or LINQ expression or something to initialize a list of objects to values instead of nulls.
Thanks!
You should ideally decide based on your application logic whether to keep this list as empty or null. One disadvantage with null is that in the places where you are not expecting this list as null, you have to add extra null checks in the application code. One better way is to initialize your list using Collections.
isEmpty() method of CollectionUtils can be used to check if a list is empty without worrying about null list. So null check is not required to be placed everywhere before checking the size of the list.
As other answers here have shown, in order to check if the list is empty you need to get the number of elements in the list ( myList. Count ) or use the LINQ method . Any() which will return true if there are any elements in the list.
Use the Enumerable.Range
LINQ method to specify the number of iterations.
List<MyObject> NewNames = Enumerable.Range(1,5).Select(i => new MyObject()).ToList();
The number 1
here is arbitrary, as the indexer is not used in any way.
Just a quick musing... you can use Enumerable.Repeat
... just not the way it's been done before. This would work:
var query = Enumerable.Repeat<Func<MyObject>>(() => new MyObject(), count)
.Select(x => x())
.ToList();
I'm not suggesting you should do this, but it's an interesting alternative to Enumerable.Range
.
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