简体   繁体   中英

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.

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);

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));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM