Problem with listing as key in dictionary collection

I have a scenario in which I use a dictionary to store a list of transaction types that a particular system accepts. The key in the dictionary is an enumeration field, the value is int.

At some point in the system, we want to do something like this:

sqlCommand.Parameters.AddWithValue("@param", LookupDictionary[argument.enumField]);

When we look at a field in a dictionary, we are going to get the correct integer value to feed into the database. I was thinking about actually using the enum int value for this, but that is not entirely correct. We interact with a system in which we need to feed a magic number in order to represent the kind of update we are doing.

The code above works fine. I have an initialization method that adds known types:

LookupDictionary = new Dictionary<mynamespace.myproject.myclass.enumType, int>();
LookupDictionary.Add(enumType.entry1, 4);
LookupDictionary.Add(enumType.entry2, 5);
LookupDictionary.Add(enumType.entry3, 6);

This code also works great.

, LookupDictionary, , , . LookupDictionary , ( enum, ).

, : . , LookupDictionary , entry2 - , entry2. enumField ; mynamespace.myproject.myclass.enumType.entry2 - , .

if (!LookupDictionary.ContainsKey(argument.enumField))
{
    throw new InvalidOperationException("argument.enumField not valid in blahMethod.");
}

, WCF? ... , .

? ? Enums, ? WCF?

: , enums magic int. , , " " 4 5 6 . , , :

public enum MyEnum
{
    MyValue1 = 4,
    MyValue2 = 5,
    MyValue3 = 6
}

, ; .

+5
4

.

:

LookupDictionary = new Dictionary<int, int>();
LookupDictionary.Add((int)enumType.entry1, 4);
LookupDictionary.Add((int)enumType.entry2, 5);
LookupDictionary.Add((int)enumType.entry3, 6);

, "ContainsKey" . , , List<int>

+3

:

public enum MyEnum
{
    MyValue1 = 4,
    MyValue2 = 5,
    MyValue3 = 6
}

// Sample usage
MyEnum firstEnum = MyEnum.MyValue1;
int intVal = (int)firstEnum;    // results in 4

// Enum Validation
bool valid = Enum.IsDefined(typeof(MyEnum), intVal);   // results in true
+1

int ( - ), ? , # ( ), SQL (, proc, , , .)

, int...

enum enumType {
    entry1 = 4,
    entry2 = 5,
    entry3 = 6
}

, .

sqlCommand.Parameters.AddWithValue("@param", (int)argument.enumField);
0

enum ArgumentTypes {
    Arg1 = 1;
    Arg2 = 3;
    Arg3 = 5;
}

You do not need to store each value in enum to use this syntax.

To verify that only those parameters that are valid for the method are used, try this sample code. Note. In this context, I suggest using the ArgumentException to throw an InvalidOperationException.

public void DoDbWork(ArgumentTypes argType, object otherParameter)
{
    if (argType == ArgumentTypes.Arg3) {
        throw new ArgumentException("Argument of value " + argType + " is not valid in this context", "argType");
    }

    // Handle db transaction here
}

To add an int value as a parameter:

cmd.Parameters.AddWithValue("@paramName", (int)argType);
0
source

All Articles