How to create a keyvalue pair with the value of two different data types?

I wrote a method that returns

List<KeyValuePair<CommandType, List<string>>> 

CommandType is of type enum

 public enum CommandType { Programmed, Manual } 

My problem is that the value in KeyValuePair sometimes enum , and sometimes it is a list of strings, but I need to keep all KeyValuePair in one list.

I am currently passing the value as an object to keyvaluepair, and when the method returns the list and repeats it, based on the key, I return the value back to its original type.

Is there a better way to implement this?

here is a sample code

 public enum ProgrammedCommands { Sntp, Snmp, } private List<KeyValuePair<CommandType, object>> GetCommandsFromTemplate(string[] templateLines) { var list = new List<KeyValuePair<CommandType, object>>(); if (templateLines != null) for (int lineIndex = 0; lineIndex < templateLines.Length; lineIndex++) { if (templateLines[lineIndex].Contains("!*") && templateLines[lineIndex].Contains("*!")) { KeyValuePair<CommandType, object> ProgrammedSetting; List<string> programmedCommandList; if (templateLines[lineIndex].Contains("SNTP - SNTP Server Commands")) { ProgrammedSetting = new KeyValuePair<CommandType, object>(CommandType.Programmed, ProgrammedCommands.Sntp); list.Add(ProgrammedSetting); } else if (templateLines[lineIndex].Contains("MANUAL")) { lineIndex++; List<string> manual = new List<string>(); while (true) { if (lineIndex >= templateLines.Length) break; if (templateLines[lineIndex].Contains("!![")) lineIndex++; else if (templateLines[lineIndex].Contains("]!!")) break; else { manual.Add(templateLines[lineIndex]); lineIndex++; } } ProgrammedSetting = new KeyValuePair<CommandType, object>(CommandType.Manual, manual); list.Add(ProgrammedSetting); } } } return list; } 
+5
source share
1 answer

If you want to use one store for different types, since the type of values ​​can only be determined at run time, then you must use the object type for box values, and then when you need to work with the value in a typed form, check its type and release it to the right type and use it.

So you can use one of these data structures based on your requirements:

  • Dictionary<CommandType, object> ← The key must be unique.
  • List<KeyValuePair<CommandType, object>> ← There, the key of the pair does not have to be unique.

Note. . You can probably imagine solutions such as creating a common BaseType base class and outputting two ListContainer and EnumContainer from BaseType and creating a ListContainer and EnumContainer at runtime and saving it in Dictionary<CommandType, BaseType> . Such structures are likely to simply help you limit the storage to the desired type, rather than using an object.

+2
source

Source: https://habr.com/ru/post/1265008/


All Articles