Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a List<T> with values that are not null

Tags:

c#

list

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!

like image 209
Bil Simser Avatar asked Jun 05 '13 15:06

Bil Simser


People also ask

Can a list be initialized as null?

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.

How do you check if a list is null or empty?

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.

How check list is null or not in C#?

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.


2 Answers

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.

like image 112
Rotem Avatar answered Sep 23 '22 09:09

Rotem


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.

like image 22
Jon Skeet Avatar answered Sep 25 '22 09:09

Jon Skeet