khaihon
khaihon

Reputation: 235

Instantiate a class object and initialize a list

Is there a way I can initialize a list in a class with existing items?

I basically would like to instantiate a class object and initialize a list with some elements already in it from existing as well as new items.

public class Item
{
    public string Property {get; set;}
}

public class MyClass
{
    public virtual IEnumerable<Item> Items {get; set;}
}

var itemToAdd = context.Items( i => i.Property == "Desired" );

MyClass myclass = new MyClass()
{
    Items = new List<Item>() 
    {
        new List<Item> (),
        { 
            Property = "New" 
        },
        // Would like itemToAdd to be added here when I create a new List.
    }
};

Upvotes: 1

Views: 8390

Answers (3)

Dominic Zukiewicz
Dominic Zukiewicz

Reputation: 8444

var itemToAdd = context.Items( i => i.Property == "Desired" );  

MyClass myclass = new MyClass() 
{     
    Items = new List<Item>(itemToAdd)  // <--####  Here    
    {         
       new List<Item> () 
       {              
           Property = "New"          
       }
    } 
};

Upvotes: 2

nickm
nickm

Reputation: 1775

You can initialize a list with data by passing a collection to the constructor. For example

var itemToAdd = context.Items( i => i.Property == "Desired" );

MyClass myclass = new MyClass()
{
    Items = new List<Item>(itemToAdd) // You can pass any collection of IEnumerable here.
}

Upvotes: 6

payo
payo

Reputation: 4561

Sure, you just add the Add method and the IEnumerable to your class

class InitEx<T> : IEnumerable<T>
{
  List<T> _data = new List<T>();

  public IEnumerator<T> GetEnumerator()
  {
    return _data.GetEnumerator();
  }

  System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
  {
    return _data.GetEnumerator();
  }

  public void Add(T i)
  {
    _data.Add(i);
  }
}

Example use

var ie = new InitEx<int> { 1, 2, 3 };

Upvotes: 0

Related Questions