7

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!

9
  • I'm not sure that this is a good idea anyway. Why do you need this?
    – SWeko
    Jun 5, 2013 at 15:12
  • The int constructor doesn't fill it with null items, it leaves the list empty but with capacity for that number of items.
    – Rawling
    Jun 5, 2013 at 15:14
  • 1
    @SWeko Why is this a bad idea? If you want a list of things that are not null there should be a simple way of initializing the list rather than having to write a loop to do so.
    – Bil Simser
    Jun 5, 2013 at 15:18
  • @Rawling If you want a list of default valued ints you could just intialize an array instead.
    – Rotem
    Jun 5, 2013 at 15:19
  • 1
    @Bil There are plenty of ways of avoiding writing the loop yourself, but that loop (or something similar) will need to exist somewhere, at some point. You can't just have the objects magically appear out of nowhere, you need to create N objects somehow.
    – Servy
    Jun 5, 2013 at 15:20

4 Answers 4

18

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.

7
  • 3
    Enumerable.Repeat(5) is ever so slightly better
    – Dave Bish
    Jun 5, 2013 at 15:13
  • 6
    Note that this will use the same reference 5 times, which isn't the same as the original code.
    – Jon Skeet
    Jun 5, 2013 at 15:17
  • @Jon Yes I just tested that and found out. Thanks, rolling back.
    – Rotem
    Jun 5, 2013 at 15:18
  • While this is elegant looking, it doesn't actually create 5 new objects. They're all the same reference like @JonSkeet said so this won't work.
    – Bil Simser
    Jun 5, 2013 at 15:21
  • 1
    @Bil Enumerable.Range does create unique references, Repeat does not.
    – Rotem
    Jun 5, 2013 at 15:22
3

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.

1

Create yourself a create and initialize function.

public List<T> CreateAndInitialize<T>(int size, Func<int, T> init)
{
  var result = new List<T>(size);
  for (int i = 0; i < size; ++i)
    result.Add(init(i));
  return result;
}

Then

List<MyObject> newNames = CreateAndInitialize(15, i => return new MyObject());

I chose to pass in the index of the object in the init delegate so that you could account for that if needed.

3
  • Note that your lambda expression would be simpler as i => new MyObject()
    – Jon Skeet
    Jun 5, 2013 at 15:17
  • I tried this but it doesn't work. result.Count is 0 after the new List<T> call. Had to rewrite it as new List<T>(size) with result.Add(init()) in the body so that works.
    – Bil Simser
    Jun 5, 2013 at 15:32
  • Based on comments, I have updated my answer. Passing the size to the ctor simply pre-allocates room for elements in the list. But the size is still 0. Jun 5, 2013 at 17:12
-1

Looks to me you are just missing the () parenthesis after the new declaration.

private List<MyObject> ObjectList = new List<MyObject>()
{
        new MyObject() { property1= Value1,  property2 = "Value2"}, 
        new MyObject() { property1= Value1,  property2 = "Value2"} 
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.