How to Create Variables Dynamically Based on List using C#?

This is my Code

Public List<string> Values{get;set;}

In the above list contains multiple values . For Example ["10","20","30"] . I want to create three variables with list values(a="10",b="20",c="30") in c#.net . If List Count is Zero No need to Create Variables.

Upvotes: 0

Views: 392

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186813

You can try using ExpandoObject:

  using System.Dynamic;

  ...

  List<string> Values = new List<string>() {
    "10", "20", "30"
  };

  ...

  dynamic variables = new ExpandoObject();

  for (int i = 0; i < Values.Count; ++i)
    (variables as IDictionary<String, Object>).Add(
       ((char) ('a' + i)).ToString(), 
       Values[i]);

  ...

  // 10
  Console.Write(variables.a);

Upvotes: 1

Kenzo_Gilead
Kenzo_Gilead

Reputation: 2439

I hope this will help you.

if (Values.Count != 0){   
    Dictionary<string, string> dictionary =
            new Dictionary<string, string>();
    char key = 'a';
    for (i = 0; i < Values.Count; i++){
        dictionary.Add(key, Values[i]);
        key = (key == 'z'? 'a': (char)(input + 1));
    }
}

Upvotes: 0

Related Questions