Home > OS >  How to assign values to an IEnumerable
How to assign values to an IEnumerable

Time:11-01

I have the following class in which I have an IEnumerable list as follows

public class Orders{
 public string No {get;set;}
 public string Id {get;set;}
 public IEnumerable<string> OrderTypes{get;set;} = new List<string>{"order 1","order 
 2","order 3"}
}

instead of me assigning the values directly above is there a way i can put it in a seperate class as follows

public class OrderTypes(){
 IEnumerable<string> myEnumberable = new List<string>()
myEnumberable.add("Order 1")
myEnumberable.add("Order 3")
myEnumberable.add("Order 4")
myEnumberable.add("Order 5")
myEnumberable.add("Order 6")
}

and then call this function above like

public class Orders{
     public string No {get;set;}
     public string Id {get;set;}
     public IEnumerable<string> OrderTypes{get;set;} = OrderTypes
}

the reason for this is cause my list gets too long and it would be easier to view, but im not sure how to achieve this.

CodePudding user response:

Close enough. You can simply use a static method:

public class Orders
{
  public string No {get;set;}
  public string Id {get;set;}
  public IEnumerable<string> OrderTypes{get;set;} = CreateOrderTypes();

  private static IEnumerable<string> CreateOrderTypes()
  {
     return new List<string>
     {
       "Order 1",
       "Order 3",
       "Order 4",
       "Order 5",
       "Order 6",
     };
   }
}

Of course, the CreateOrderTypes does not have to be in the same class and can be moved to a different class. The second class has to be visible to the first one.

public class Orders
{
  public string No {get;set;}
  public string Id {get;set;}
  public IEnumerable<string> OrderTypes{get;set;} = OrderTypesFactory.InitOrderTypes();
}

static class OrderTypesFactory
{
  static IEnumerable<string> InitOrderTypes()
  {
     return new List<string>
     {
       "Order 1",
       "Order 3",
       "Order 4",
       "Order 5",
       "Order 6",
     };
   }
}

CodePudding user response:

If I understand the question correctly, you could have a constructor for class Orders and then when you instantiate the class, you could pass a value of IEnumerable inside it and assign that value. So it would look something like:

public class Orders
{
    public string No { get; set; }
    public string Id { get; set; }
    public IEnumerable<string> OrderTypes { get; set; }

    public Orders(IEnumerable<string> orderTypes)
    {
        OrderTypes = orderTypes;
    }

}

public class Main
{
    public void Main()
    {
        var orderTypes = new List<string>() { "Your", "values", "Here" };
        var orders = new Orders(orderTypes);
    }
}
  • Related